Crea sito

Content



SplFileInfo::getLinkTarget

(PHP 5 >= 5.2.2)

SplFileInfo::getLinkTargetGets the target of a link

Descrizione

public string SplFileInfo::getLinkTarget ( void )

Gets the target of a filesystem link.

Nota:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the target of the filesystem link.

Errori/Eccezioni

Throws RuntimeException on error.

Esempi

Example #1 SplFileInfo::getLinkTarget() example

<?php
$info 
= new SplFileInfo('/Users/bbieber/workspace');
if (
$info->isLink()) {
    
var_dump($info->getLinkTarget());
    
var_dump($info->getRealPath());
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

Vedere anche:



SplFileInfo::getMTime

(PHP 5 >= 5.1.2)

SplFileInfo::getMTimeGets the last modified time

Descrizione

public int SplFileInfo::getMTime ( void )

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the last modified time for the file, in a Unix timestamp.

Vedere anche:

  • filemtime() - Restituisce l'ora delle modifiche al file



SplFileInfo::getOwner

(PHP 5 >= 5.1.2)

SplFileInfo::getOwnerGets the owner of the file

Descrizione

public int SplFileInfo::getOwner ( void )

Gets the file owner. The owner ID is returned in numerical format.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

The owner id in numerical format.

Errori/Eccezioni

Throws RuntimeException on error.

Esempi

Example #1 SplFileInfo::getOwner() example

<?php
$info 
= new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>

Vedere anche:



SplFileInfo::getPath

(PHP 5 >= 5.1.2)

SplFileInfo::getPathGets the path without filename

Descrizione

public string SplFileInfo::getPath ( void )

Returns the path to the file, omitting the filename and any trailing slash.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the path to the file.

Esempi

Example #1 SplFileInfo::getPath() example

<?php
$info 
= new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());


$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

Il precedente esempio visualizzerà qualcosa simile a:

string(8) "/usr/bin"
string(4) "/usr"

Vedere anche:



SplFileInfo::getPathInfo

(PHP 5 >= 5.1.2)

SplFileInfo::getPathInfoGets an SplFileInfo object for the path

Descrizione

public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )

Gets an SplFileInfo object for the parent of the current file.

Elenco dei parametri

class_name

Name of an SplFileInfo derived class to use.

Valori restituiti

Returns an SplFileInfo object for the parent path of the file.

Esempi

Example #1 SplFileInfo::getPathInfo() example

<?php
$info 
= new SplFileInfo('/usr/bin/php');
$parent_info $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(8) "/usr/bin"

Vedere anche:



SplFileInfo::getPathname

(PHP 5 >= 5.1.2)

SplFileInfo::getPathnameGets the path to the file

Descrizione

public string SplFileInfo::getPathname ( void )

Returns the path to the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

The path to the file.

Esempi

Example #1 SplFileInfo::getPathname() example

<?php
$info 
= new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(12) "/usr/bin/php"

Vedere anche:



SplFileInfo::getPerms

(PHP 5 >= 5.1.2)

SplFileInfo::getPermsGets file permissions

Descrizione

public int SplFileInfo::getPerms ( void )

Gets the file permissions for the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the file permissions.

Esempi

Example #1 SplFileInfo::getPerms() example

<?php
$info 
= new SplFileInfo('/tmp');
echo 
substr(sprintf('%o'$info->getPerms()), -4);

$info = new SplFileInfo(__FILE__);
echo 
substr(sprintf('%o'$info->getPerms()), -4);
?>

Il precedente esempio visualizzerà qualcosa simile a:

1777
0644



SplFileInfo::getRealPath

(PHP 5 >= 5.2.2)

SplFileInfo::getRealPathGets absolute path to file

Descrizione

public string SplFileInfo::getRealPath ( void )

This method expands all symbolic links, resolves relative references and returns the real path to the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the path to the file.

Esempi

Example #1 SplFileInfo::getRealPath() example

<?php
$info 
= new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(28) "/private/tmp/phptempfile.php" 
string(12) "/private/tmp"

Vedere anche:



SplFileInfo::getSize

(PHP 5 >= 5.1.2)

SplFileInfo::getSizeGets file size

Descrizione

public int SplFileInfo::getSize ( void )

Returns the filesize in bytes for the file referenced.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

The filesize in bytes.

Errori/Eccezioni

A RuntimeException will be thrown if the file does not exist or an error occurs.

Vedere anche:



SplFileInfo::getType

(PHP 5 >= 5.1.2)

SplFileInfo::getTypeGets file type

Descrizione

public string SplFileInfo::getType ( void )

Returns the type of the file referenced.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

A string representing the type of the entry. May be one of file, link, or dir

Errori/Eccezioni

Throws a RuntimeException on error.

Esempi

Example #1 SplFileInfo::getType() example

<?php

$info 
= new SplFileInfo(__FILE__);
echo 
$info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo 
$info->getType();

?>

Il precedente esempio visualizzerà qualcosa simile a:

file
dir



SplFileInfo::isDir

(PHP 5 >= 5.1.2)

SplFileInfo::isDirTells if the file is a directory

Descrizione

public bool SplFileInfo::isDir ( void )

This method can be used to determine if the file is a directory.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if a directory, FALSE otherwise.

Esempi

Example #1 SplFileInfo::isDir() example

<?php
$d 
= new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(true)
bool(false)



SplFileInfo::isExecutable

(PHP 5 >= 5.1.2)

SplFileInfo::isExecutableTells if the file is executable

Descrizione

public bool SplFileInfo::isExecutable ( void )

Checks if the file is executable.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if executable, FALSE otherwise.

Esempi

Example #1 SplFileInfo::isExecutable() example

<?php
$info 
= new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable()); 

$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());

$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(true)
bool(true)
bool(false)



SplFileInfo::isFile

(PHP 5 >= 5.1.2)

SplFileInfo::isFileTells if the object references a regular file

Descrizione

public bool SplFileInfo::isFile ( void )

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if the file exists and is a regular file (not a link), FALSE otherwise.

Esempi

Example #1 SplFileInfo::isFile() example

<?php
$info 
= new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(true)
bool(false)




SplFileInfo::isReadable

(PHP 5 >= 5.1.2)

SplFileInfo::isReadableTells if file is readable

Descrizione

public bool SplFileInfo::isReadable ( void )

Check if the file is readable.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if readable, FALSE otherwise.

Esempi

Example #1 SplFileInfo::isReadable() example

<?php
$info 
= new SplFileInfo(__FILE__);
var_dump($info->isReadable());

$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(true)
bool(false)



SplFileInfo::isWritable

(PHP 5 >= 5.1.2)

SplFileInfo::isWritableTells if the entry is writable

Descrizione

public bool SplFileInfo::isWritable ( void )

Checks if the current entry is writable.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if writable, FALSE otherwise;



SplFileInfo::openFile

(PHP 5 >= 5.1.2)

SplFileInfo::openFileGets an SplFileObject object for the file

Descrizione

public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )

Creates an SplFileObject object of the file. This is useful because SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.

Elenco dei parametri

open_mode

The mode for opening the file. See the fopen() documentation for descriptions of possible modes. The default is read only.

use_include_path

Qundo impostato a TRUE, il nome del the file è cercato anche all'interno di include_path

context

Vedere la sezione contesto del manuale per una descrizion dei contesti.

Valori restituiti

The opened file as an SplFileObject object.

Errori/Eccezioni

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

Esempi

Example #1 SplFileInfo::openFile() example

<?php
$fileinfo 
= new SplFileInfo('/tmp/foo.txt');

if (
$fileinfo->isWritable()) {

    
$fileobj $fileinfo->openFile('a');

    
$fileobj->fwrite("appended this sample text");
}
?>

Vedere anche:



SplFileInfo::setFileClass

(PHP 5 >= 5.1.2)

SplFileInfo::setFileClassSets the class name used with SplFileInfo::openFile()

Descrizione

public void SplFileInfo::setFileClass ([ string $class_name ] )

Set the class name which SplFileInfo will use to open files with when openFile() is called. The class name passed to this method must be derived from SplFileObject.

Elenco dei parametri

class_name

The class name to use when openFile() is called.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 SplFileInfo::setFileClass() example

<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}

$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>

Il precedente esempio visualizzerà qualcosa simile a:

object(MyFoo)#2 (0) { } 

Vedere anche:



SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2)

SplFileInfo::setInfoClassSets the class used with getFileInfo and getPathInfo

Descrizione

public void SplFileInfo::setInfoClass ([ string $class_name ] )

Use this method to set a custom class which will be used when getFileInfo and getPathInfo are called. The class name passed to this method must be derived from SplFileInfo.

Elenco dei parametri

class_name

The class name to use.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 SplFileInfo::setFileClass() example

<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}

$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>

Il precedente esempio visualizzerà qualcosa simile a:

object(MyFoo)#2 (0) { } 

Vedere anche:



SplFileInfo::__toString

(PHP 5 >= 5.1.2)

SplFileInfo::__toStringReturns the path to the file as a string

Descrizione

public void SplFileInfo::__toString ( void )

This method will return the file name of the referenced file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the path to the file.

Esempi

Example #1 SplFileInfo::__toString() example

<?php
$info 
= new SplFileInfo('foo');
var_dump($info->__toString());
echo 
$info.PHP_EOL;

$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo 
$info.PHP_EOL;
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php 


Indice dei contenuti



The SplFileObject class

(PHP 5 >= 5.1.0)

Introduzione

The SplFileObject class offers an object oriented interface for a file.

Sommario dellla classe

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {
/* Costanti */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 4 ;
const integer READ_CSV = 8 ;
/* Metodi */
public __construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array current ( void )
public bool eof ( void )
public bool fflush ( void )
public string fgetc ( void )
public array fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public string fgets ( void )
public string fgetss ([ string $allowable_tags ] )
public bool flock ( int $operation [, int &$wouldblock ] )
public int fpassthru ( void )
public int fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
public mixed fscanf ( string $format [, mixed &$... ] )
public int fseek ( int $offset [, int $whence = SEEK_SET ] )
public array fstat ( void )
public int ftell ( void )
public bool ftruncate ( int $size )
public int fwrite ( string $str [, int $length ] )
public void getChildren ( void )
public array getCsvControl ( void )
public int getFlags ( void )
public int getMaxLineLen ( void )
public bool hasChildren ( void )
public int key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $line_pos )
public void setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public void setFlags ( int $flags )
public void setMaxLineLen ( int $max_len )
public void __toString ( void )
public bool valid ( void )
/* Metodi ereditati */
public SplFileInfo::__construct ( string $file_name )
public int SplFileInfo::getATime ( void )
public string SplFileInfo::getBasename ([ string $suffix ] )
public int SplFileInfo::getCTime ( void )
public string SplFileInfo::getExtension ( void )
public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )
public string SplFileInfo::getFilename ( void )
public int SplFileInfo::getGroup ( void )
public int SplFileInfo::getInode ( void )
public string SplFileInfo::getLinkTarget ( void )
public int SplFileInfo::getMTime ( void )
public int SplFileInfo::getOwner ( void )
public string SplFileInfo::getPath ( void )
public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )
public string SplFileInfo::getPathname ( void )
public int SplFileInfo::getPerms ( void )
public string SplFileInfo::getRealPath ( void )
public int SplFileInfo::getSize ( void )
public string SplFileInfo::getType ( void )
public bool SplFileInfo::isDir ( void )
public bool SplFileInfo::isExecutable ( void )
public bool SplFileInfo::isFile ( void )
public bool SplFileInfo::isLink ( void )
public bool SplFileInfo::isReadable ( void )
public bool SplFileInfo::isWritable ( void )
public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void SplFileInfo::setFileClass ([ string $class_name ] )
public void SplFileInfo::setInfoClass ([ string $class_name ] )
public void SplFileInfo::__toString ( void )
}

Costanti predefinite

SplFileObject::DROP_NEW_LINE

Drop newlines at the end of a line.

SplFileObject::READ_AHEAD

Read on rewind/next.

SplFileObject::SKIP_EMPTY

Skips empty lines in the file. This requires the READ_AHEAD flag be enabled, to work as expected.

SplFileObject::READ_CSV

Read lines as CSV rows.

Log delle modifiche

Versione Descrizione
5.3.9 SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.


SplFileObject::__construct

(PHP 5 >= 5.1.0)

SplFileObject::__constructConstruct a new file object.

Descrizione

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )

Construct a new file object.

Elenco dei parametri

filename

The file to read.

Suggerimento

È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Vedere fopen() per maggiori informazioni su come specificare i nomi di file. Vedere Supported Protocols and Wrappers per i link verso le informazioni sulle capacità dei vari wrapper, note sul loro uso, informazioni sulle variabili predefinite che forniscono.

open_mode

The mode in which to open the file. See fopen() for a list of allowed modes.

use_include_path

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

Valori restituiti

Nessun valore viene restituito.

Errori/Eccezioni

Throws a RuntimeException if the filename cannot be opened.

Esempi

Example #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file 
= new SplFileObject(__FILE__);
foreach (
$file as $line_num => $line) {
    echo 
"Line $line_num is $line";
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

Vedere anche:



SplFileObject::current

(PHP 5 >= 5.1.0)

SplFileObject::currentRetrieve current line of file

Descrizione

public string|array SplFileObject::current ( void )

Retrieves the current line of the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data.

Esempi

Example #1 SplFileObject::current() example

<?php
$file 
= new SplFileObject(__FILE__);
foreach (
$file as $k => $line) {
   echo (
$file->key() + 1) . ': ' $file->current();
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

Vedere anche:



SplFileObject::eof

(PHP 5 >= 5.1.0)

SplFileObject::eofReached end of file

Descrizione

public bool SplFileObject::eof ( void )

Determine whether the end of file has been reached

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if file is at EOF, FALSE otherwise.

Esempi

Example #1 SplFileObject::eof() example

<?php
$file 
= new SplFileObject("fruits.txt");
while ( ! 
$file->eof()) {
    echo 
$file->fgets();
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

apple
banana
cherry
date
elderberry

Vedere anche:



SplFileObject::fflush

(PHP 5 >= 5.1.0)

SplFileObject::fflushFlushes the output to the file

Descrizione

public bool SplFileObject::fflush ( void )

Forces a write of all buffered output to the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 SplFileObject::fflush() example

<?php
$file 
= new SplFileObject('misc.txt''r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

Vedere anche:



SplFileObject::fgetc

(PHP 5 >= 5.1.0)

SplFileObject::fgetcGets character from file

Descrizione

public string SplFileObject::fgetc ( void )

Gets a character from the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns a string containing a single character read from the file or FALSE on EOF.

Avviso

Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE. Fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione.

Esempi

Example #1 SplFileObject::fgetc() example

<?php
$file 
= new SplFileObject('file.txt');
while (
false !== ($char $file->fgetc())) {
    echo 
"$char\n";
}
?>

Vedere anche:



SplFileObject::fgetcsv

(PHP 5 >= 5.1.0)

SplFileObject::fgetcsvGets line from file and parse as CSV fields

Descrizione

public array SplFileObject::fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Elenco dei parametri

delimiter

The field delimiter (one character only). Defaults as a comma or the value set using SplFileObject::setCsvControl().

enclosure

The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().

escape

The escape character (one character only). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl().

Valori restituiti

Returns an indexed array containing the fields read, or FALSE on error.

Nota:

A blank line in a CSV file will be returned as an array comprising a single NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

Esempi

Example #1 SplFileObject::fgetcsv() example

<?php
$file 
= new SplFileObject("data.csv");
while (!
$file->eof()) {
    
var_dump($file->fgetcsv());
}
?>

Example #2 SplFileObject::READ_CSV example

<?php
$file 
= new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach (
$file as $row) {
    list(
$animal$class$legs) = $row;
    
printf("A %s is a %s with %d legs\n"$animal$class$legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

Il precedente esempio visualizzerà qualcosa simile a:

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

Vedere anche:



SplFileObject::fgets

(PHP 5 >= 5.1.0)

SplFileObject::fgetsGets line from file

Descrizione

public string SplFileObject::fgets ( void )

Gets a line from the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns a string containing the next line from the file, or FALSE on error.

Errori/Eccezioni

Throws a RuntimeException if the file cannot be read.

Esempi

Example #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file 
= new SplFileObject("file.txt");
while (!
$file->eof()) {
    echo 
$file->fgets();
}
?>

Vedere anche:



SplFileObject::fgetss

(PHP 5 >= 5.1.0)

SplFileObject::fgetssGets line from file and strip HTML tags

Descrizione

public string SplFileObject::fgetss ([ string $allowable_tags ] )

Identical to SplFileObject::fgets(), except that SplFileObject::fgetss() attempts to strip any HTML and PHP tags from the text it reads.

Elenco dei parametri

allowable_tags

Optional parameter to specify tags which should not be stripped.

Valori restituiti

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Esempi

Example #1 SplFileObject::fgetss() example

<?php
$str 
= <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php"$str);

$file = new SplFileObject("sample.php");
while (!
$file->eof()) {
    echo 
$file->fgetss();
}
?>

Il precedente esempio visualizzerà qualcosa simile a:


 Welcome! Today is the  of .

Text outside of the HTML block.

Vedere anche:



SplFileObject::flock

(PHP 5 >= 5.1.0)

SplFileObject::flockPortable file locking

Descrizione

public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )

Locks or unlocks the file in the same portable way as flock().

Elenco dei parametri

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB to not block while locking (not supported on Windows).

wouldblock

Set to TRUE if the lock would block (EWOULDBLOCK errno condition).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 SplFileObject::flock() example

<?php
$file 
= new SplFileObject("/tmp/lock.txt""w");
if (
$file->flock(LOCK_EX)) { // do an exclusive lock
    
$file->ftruncate(0);     // truncate file
    
$file->fwrite("Write something here\n");
    
$file->flock(LOCK_UN);   // release the lock    
} else {
    echo 
"Couldn't get the lock!";
}
?>

Vedere anche:

  • flock() - Sistema di bloccaggio file



SplFileObject::fpassthru

(PHP 5 >= 5.1.0)

SplFileObject::fpassthruOutput all remaining data on a file pointer

Descrizione

public int SplFileObject::fpassthru ( void )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call SplFileObject::rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the number of characters read from handle and passed through to the output.

Esempi

Example #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png""rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

Vedere anche:

  • fpassthru() - Invia tutti i dati rimanenti su un puntartore a file



SplFileObject::fputcsv

(PHP 5 >= 5.4.0)

SplFileObject::fputcsvWrite a field array as a CSV line

Descrizione

public int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )

Writes the fields array to the file as a CSV line.

Elenco dei parametri

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

Valori restituiti

Returns the length of the written string o FALSE in caso di fallimento.

Returns FALSE, and does not write the CSV line to the file, if the delimiter or enclosure parameter is not a single character.

Errori/Eccezioni

An E_WARNING level error is issued if the delimiter or enclosure parameter is not a single character.

Esempi

Example #1 SplFileObject::fputcsv() example

<?php

$list 
= array (
    array(
'aaa''bbb''ccc''dddd'),
    array(
'123''456''789'),
    array(
'"aaa"''"bbb"')
);

$file = new SplFileObject('file.csv''w');

foreach (
$list as $fields) {
    
$file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Vedere anche:



SplFileObject::fscanf

(PHP 5 >= 5.1.0)

SplFileObject::fscanfParses input from file according to a format

Descrizione

public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab \t in the format string can match a single space character in the input stream.

Elenco dei parametri

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Valori restituiti

If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Esempi

Example #1 SplFileObject::fscanf() example

<?php
$file 
= new SplFileObject("misc.txt");
while (
$userinfo $file->fscanf("%s %s %s")) {
    list (
$name$profession$countrycode) = $userinfo;
    
// Do something with $name $professi
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

Vedere anche:

  • fscanf() - Analizza l'input da un file secondo un determinato formato



SplFileObject::fseek

(PHP 5 >= 5.1.0)

SplFileObject::fseekSeek to a position

Descrizione

public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

Elenco dei parametri

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Valori restituiti

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Esempi

Example #1 SplFileObject::fseek() example

<?php
$file 
= new SplFileInfo("somefile.txt");

// Read first line
$data $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

Vedere anche:

  • fseek() - Sposta un puntatore sul file



SplFileObject::fstat

(PHP 5 >= 5.1.0)

SplFileObject::fstatGets information about the file

Descrizione

public array SplFileObject::fstat ( void )

Gathers the statistics of the file. Behaves identically to fstat().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Esempi

Example #1 SplFileObject::fstat() example

<?php
$file 
= new SplFileObject("/etc/passwd");
$stat $file->fstat();

// Print only the associative part
print_r(array_slice($stat13));

?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

Vedere anche:

  • fstat() - Restituisce le informazioni riguardanti un file attraverso un puntatore al file aperto
  • stat() - Da informazioni su un file



SplFileObject::ftell

(PHP 5 >= 5.1.0)

SplFileObject::ftellReturn current file position

Descrizione

public int SplFileObject::ftell ( void )

Returns the position of the file pointer which represents the current offset in the file stream.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the position of the file pointer as an integer, or FALSE on error.

Esempi

Example #1 SplFileObject::ftell() example

<?php
$file 
= new SplFileObject("/etc/passwd");

// Read first line
$data $file->fgets();

// Where are we?
echo $file->ftell();
?>

Vedere anche:

  • ftell() - Comunica la posizione di lettura/scrittura del puntatore al file



SplFileObject::ftruncate

(PHP 5 >= 5.1.0)

SplFileObject::ftruncateTruncates the file to a given length

Descrizione

public bool SplFileObject::ftruncate ( int $size )

Truncates the file to size bytes.

Elenco dei parametri

size

The size to truncate to.

Nota:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate""w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo 
$file->fgets();
?>

Il precedente esempio visualizzerà qualcosa simile a:

Hello

Vedere anche:



SplFileObject::fwrite

(PHP 5 >= 5.1.0)

SplFileObject::fwriteWrite to file

Descrizione

public int SplFileObject::fwrite ( string $str [, int $length ] )

Writes the contents of string to the file

Elenco dei parametri

str

The string to be written to the file.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Valori restituiti

Returns the number of bytes written, or NULL on error.

Esempi

Example #1 SplFileObject::fwrite() example

<?php
$file 
= new SplFileObject("fwrite.txt""w");
$written $file->fwrite("12345");
echo 
"Wrote $written bytes to file";
?>

Il precedente esempio visualizzerà qualcosa simile a:

Wrote 5 bytes to file

Vedere anche:

  • fwrite() - Scrive un file salvaguardando la corrispondenza binaria



SplFileObject::getChildren

(PHP 5 >= 5.1.0)

SplFileObject::getChildrenNo purpose

Descrizione

public void SplFileObject::getChildren ( void )

An SplFileObject does not have children so this method returns NULL.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Vedere anche:



SplFileObject::getCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::getCsvControlGet the delimiter and enclosure character for CSV

Descrizione

public array SplFileObject::getCsvControl ( void )

Gets the delimiter and enclosure character used for parsing CSV fields.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns an indexed array containing the delimiter and enclosure character.

Esempi

Example #1 SplFileObject::getCsvControl() example

<?php
$file 
= new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

Il precedente esempio visualizzerà qualcosa simile a:

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

Vedere anche:



SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2)

SplFileObject::getCurrentLineAlias of SplFileObject::fgets()

Descrizione

This method is an alias of SplFileObject::fgets().



SplFileObject::getFlags

(PHP 5 >= 5.1.0)

SplFileObject::getFlagsGets flags for the SplFileObject

Descrizione

public int SplFileObject::getFlags ( void )

Gets the flags set for an instance of SplFileObject as an integer.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns an integer representing the flags.

Esempi

Example #1 SplFileObject::getFlags() example

<?php
$file 
= new SplFileObject(__FILE__"r");

if (
$file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo 
"Skipping empty lines\n";
} else {
    echo 
"Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if (
$file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo 
"Skipping empty lines\n";
} else {
    echo 
"Not skipping empty lines\n";
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

Not skipping empty lines
Skipping empty lines

Vedere anche:



SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::getMaxLineLenGet maximum line length

Descrizione

public int SplFileObject::getMaxLineLen ( void )

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

Esempi

Example #1 SplFileObject::getMaxLineLen() example

<?php
$file 
= new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

Il precedente esempio visualizzerà qualcosa simile a:

int(0)
int(20)

Vedere anche:

  • Classname::Method()



SplFileObject::hasChildren

(PHP 5 >= 5.1.2)

SplFileObject::hasChildrenSplFileObject does not have children

Descrizione

public bool SplFileObject::hasChildren ( void )

An SplFileObject does not have children so this method always return FALSE.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns FALSE

Vedere anche:



SplFileObject::key

(PHP 5 >= 5.1.0)

SplFileObject::keyGet line number

Descrizione

public int SplFileObject::key ( void )

Gets the current line number.

Nota:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the current line number.

Esempi

Example #1 SplFileObject::key() example

<?php
$file 
= new SplFileObject("lipsum.txt");
foreach (
$file as $line) {
    echo 
$file->key() . ". " $line;
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
1. Duis nec sapien felis, ac sodales nisl. 
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Example #2 SplFileObject::key() example with SplFileObject::setMaxLineLen()

<?php
$file 
= new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach (
$file as $line) {
    echo 
$file->key() . ". " $line "\n";
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit. 
3. 

4. Duis nec sapien fel
5. is, ac sodales nisl
6. . 

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

Vedere anche:



SplFileObject::next

(PHP 5 >= 5.1.0)

SplFileObject::nextRead next line

Descrizione

public void SplFileObject::next ( void )

Moves ahead to the next line in the file.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!
$file->eof()) {
    echo 
$file->current();
    
$file->next();
}
?>

Vedere anche:



SplFileObject::rewind

(PHP 5 >= 5.1.0)

SplFileObject::rewindRewind the file to the first line

Descrizione

public void SplFileObject::rewind ( void )

Rewinds the file back to the first line.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Errori/Eccezioni

Throws a RuntimeException if cannot be rewound.

Esempi

Example #1 SplFileObject::rewind() example

<?php
$file 
= new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

Vedere anche:



SplFileObject::seek

(PHP 5 >= 5.1.0)

SplFileObject::seekSeek to specified line

Descrizione

public void SplFileObject::seek ( int $line_pos )

Seek to specified line in the file.

Elenco dei parametri

line_pos

The zero-based line number to seek to.

Valori restituiti

Nessun valore viene restituito.

Errori/Eccezioni

Throws a LogicException if the line_pos is negative.

Esempi

Example #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file 
= new SplFileObject(__FILE__);
$file->seek(2);
echo 
$file->current();
?>

Il precedente esempio visualizzerà qualcosa simile a:

$file->seek(2);

Vedere anche:



SplFileObject::setCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::setCsvControlSet the delimiter and enclosure character for CSV

Descrizione

public void SplFileObject::setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )

Sets the delimiter and enclosure character for parsing CSV fields.

Elenco dei parametri

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (one character only).

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 SplFileObject::setCsvControl() example

<?php
$file 
= new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach (
$file as $row) {
    list (
$fruit$quantity) = $row;
    
// Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

Vedere anche:



SplFileObject::setFlags

(PHP 5 >= 5.1.0)

SplFileObject::setFlagsSets flags for the SplFileObject

Descrizione

public void SplFileObject::setFlags ( int $flags )

Sets the flags to be used by the SplFileObject.

Elenco dei parametri

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 SplFileObject::setFlags() example

<?php
$file 
= new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach (
$file as $fields) {
    
var_dump($fields);
}
?>

Vedere anche:



SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::setMaxLineLenSet maximum line length

Descrizione

public void SplFileObject::setMaxLineLen ( int $max_len )

Sets the maximum length of a line to be read.

Elenco dei parametri

max_len

The maximum length of a line.

Valori restituiti

Nessun valore viene restituito.

Errori/Eccezioni

Throws DomainException when max_len is less than zero.

Esempi

Example #1 SplFileObject::setMaxLineLen() example

<?php
$file 
= new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach (
$file as $line) {
    echo 
$line "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

Il precedente esempio visualizzerà qualcosa simile a:

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet 
consequat.

Vedere anche:

  • Classname::Method()



SplFileObject::__toString

(PHP 5 >= 5.1.0)

SplFileObject::__toStringAlias of SplFileObject::current()

Descrizione

public void SplFileObject::__toString ( void )

This method is an alias of SplFileObject::current().



SplFileObject::valid

(PHP 5 >= 5.1.0)

SplFileObject::validNot at EOF

Descrizione

public bool SplFileObject::valid ( void )

Check whether EOF has been reached.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns TRUE if not reached EOF, FALSE otherwise.

Esempi

Example #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while (
$file->valid()) {
    echo 
$file->fgets();
}
?>

Vedere anche:


Indice dei contenuti



The SplTempFileObject class

(PHP 5 >= 5.1.2)

Introduzione

The SplTempFileObject class offers an object oriented interface for a temporary file.

Sommario dellla classe

SplTempFileObject extends SplFileObject implements SeekableIterator , RecursiveIterator {
/* Metodi */
public __construct ([ int $max_memory ] )
/* Metodi ereditati */
public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array SplFileObject::current ( void )
public bool SplFileObject::eof ( void )
public bool SplFileObject::fflush ( void )
public string SplFileObject::fgetc ( void )
public array SplFileObject::fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public string SplFileObject::fgets ( void )
public string SplFileObject::fgetss ([ string $allowable_tags ] )
public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )
public int SplFileObject::fpassthru ( void )
public int SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )
public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )
public array SplFileObject::fstat ( void )
public int SplFileObject::ftell ( void )
public bool SplFileObject::ftruncate ( int $size )
public int SplFileObject::fwrite ( string $str [, int $length ] )
public void SplFileObject::getChildren ( void )
public array SplFileObject::getCsvControl ( void )
public int SplFileObject::getFlags ( void )
public int SplFileObject::getMaxLineLen ( void )
public bool SplFileObject::hasChildren ( void )
public int SplFileObject::key ( void )
public void SplFileObject::next ( void )
public void SplFileObject::rewind ( void )
public void SplFileObject::seek ( int $line_pos )
public void SplFileObject::setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public void SplFileObject::setFlags ( int $flags )
public void SplFileObject::setMaxLineLen ( int $max_len )
public void SplFileObject::__toString ( void )
public bool SplFileObject::valid ( void )
}

SplTempFileObject::__construct

(PHP 5 >= 5.1.2)

SplTempFileObject::__constructConstruct a new temporary file object

Descrizione

public SplTempFileObject::__construct ([ int $max_memory ] )

Construct a new temporary file object.

Elenco dei parametri

max_memory

The maximum amount of memory (in bytes, default is 2 MB) for the temporary file to use. If the temporary file exceeds this size, it will be moved to a file in the system's temp directory.

If max_memory is negative, only memory will be used. If max_memory is zero, no memory will be used.

Valori restituiti

Nessun valore viene restituito.

Errori/Eccezioni

Throws a RuntimeException if an error occurs.

Esempi

Example #1 SplTempFileObject() example

This example writes a temporary file in memory which can be written to and read from.

<?php
$temp 
= new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo 
"Written " $temp->ftell() . " bytes to temporary file.\n\n";

// Rewind and read what was written
$temp->rewind();
foreach (
$temp as $line) {
    echo 
$line;
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

Written 47 bytes to temporary file.

This is the first line
And this is the second.

Vedere anche:


Indice dei contenuti




Miscellaneous Classes and Interfaces

Indice dei contenuti

Classes and interfaces which do not fit into the other SPL categories.


The ArrayObject class

(PHP 5)

Introduzione

This class allows objects to work as arrays.

Sommario dellla classe

ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable {
/* Costanti */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Metodi */
public __construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )
public void append ( mixed $value )
public void asort ( void )
public int count ( void )
public array exchangeArray ( mixed $input )
public array getArrayCopy ( void )
public int getFlags ( void )
public ArrayIterator getIterator ( void )
public string getIteratorClass ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public string serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callable $cmp_function )
public void uksort ( callable $cmp_function )
public void unserialize ( string $serialized )
}

Costanti predefinite

ArrayObject Flags

ArrayObject::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Log delle modifiche

Versione Descrizione
5.3.0 Implements Serializable.


ArrayObject::append

(PHP 5 >= 5.0.0)

ArrayObject::appendAppends the value

Descrizione

public void ArrayObject::append ( mixed $value )

Appends a new value as the last element.

Nota:

This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

Elenco dei parametri

value

The value being appended.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::append() example

<?php
$arrayobj 
= new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five''six'));
var_dump($arrayobj);
?>

Il precedente esempio visualizzerà:

object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

Vedere anche:



ArrayObject::asort

(PHP 5 >= 5.2.0)

ArrayObject::asortSort the entries by value

Descrizione

public void ArrayObject::asort ( void )

Sorts the entries such that the keys maintain their correlation with the entries they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::asort() example

<?php
$fruits 
= array("d" => "lemon""a" => "orange""b" => "banana""c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach (
$fruitArrayObject as $key => $val) {
    echo 
"$key = $val\n";
}
?>

Il precedente esempio visualizzerà:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained.

Vedere anche:



ArrayObject::__construct

(PHP 5 >= 5.0.0)

ArrayObject::__constructConstruct a new array object

Descrizione

public ArrayObject::__construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )

This constructs a new array object.

Elenco dei parametri

input

The input parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().

iterator_class

Specify the class that will be used for iteration of the ArrayObject object.

Valori restituiti

Returns an ArrayObject object on success.

Errori/Eccezioni

Throws InvalidArgumentException when:

  • input is not an array or object
  • flags is not an integer
  • iterator_class is not an object that implements Iterator

Esempi

Example #1 ArrayObject::__construct() example

<?php
$array 
= array('1' => 'one',
               
'2' => 'two',
               
'3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

Il precedente esempio visualizzerà:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

Vedere anche:



ArrayObject::count

(PHP 5 >= 5.0.0)

ArrayObject::countGet the number of public properties in the ArrayObject

Descrizione

public int ArrayObject::count ( void )

Get the number of public properties in the ArrayObject.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

The number of public properties in the ArrayObject.

Nota:

When the ArrayObject is constructed from an array all properties are public.

Esempi

Example #1 ArrayObject::count() example

<?php
class Example {
    public 
$public 'prop:public';
    private 
$prv   'prop:private';
    protected 
$prt 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

Il precedente esempio visualizzerà:

int(1)
int(3)



ArrayObject::exchangeArray

(PHP 5 >= 5.1.0)

ArrayObject::exchangeArrayExchange the array for another one.

Descrizione

public array ArrayObject::exchangeArray ( mixed $input )

Exchange the current array with another array or object.

Elenco dei parametri

input

The new array or object to exchange with the current array.

Valori restituiti

Returns the old array.

Esempi

Example #1 ArrayObject::exchangeArray() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam''Paris''London');

$fruitsArrayObject = new ArrayObject($fruits);

// Now exchange fruits for locations
$old $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);

?>

Il precedente esempio visualizzerà:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)
ArrayObject Object
(
    [0] => Amsterdam
    [1] => Paris
    [2] => London
)



ArrayObject::getArrayCopy

(PHP 5 >= 5.0.0)

ArrayObject::getArrayCopyCreates a copy of the ArrayObject.

Descrizione

public array ArrayObject::getArrayCopy ( void )

Exports the ArrayObject to an array.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns a copy of the array. When the ArrayObject refers to an object an array of the public properties of that object will be returned.

Esempi

Example #1 ArrayObject::getArrayCopy() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

Il precedente esempio visualizzerà:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
    [pears] => 4
)



ArrayObject::getFlags

(PHP 5 >= 5.1.0)

ArrayObject::getFlagsGets the behavior flags.

Descrizione

public int ArrayObject::getFlags ( void )

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the behavior flags of the ArrayObject.

Esempi

Example #1 ArrayObject::getFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current flags
$flags $fruitsArrayObject->getFlags();
var_dump($flags);

// Set new flags
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);

// Get the new flags
$flags $fruitsArrayObject->getFlags();
var_dump($flags);
?>

Il precedente esempio visualizzerà:

int(0)
int(2)

Vedere anche:



ArrayObject::getIterator

(PHP 5 >= 5.0.0)

ArrayObject::getIteratorCreate a new iterator from an ArrayObject instance

Descrizione

public ArrayIterator ArrayObject::getIterator ( void )

Create a new iterator from an ArrayObject instance.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

An iterator from an ArrayObject.

Esempi

Example #1 ArrayObject::getIterator() example

<?php
$array 
= array('1' => 'one',
               
'2' => 'two',
               
'3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator $arrayobject->getIterator();

while(
$iterator->valid()) {
    echo 
$iterator->key() . ' => ' $iterator->current() . "\n";

    
$iterator->next();
}
?>

Il precedente esempio visualizzerà:

1 => one
2 => two
3 => three



ArrayObject::getIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::getIteratorClassGets the iterator classname for the ArrayObject.

Descrizione

public string ArrayObject::getIteratorClass ( void )

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the iterator class name that is used to iterate over this object.

Esempi

Example #1 ArrayObject::getIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    
// custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current class name
$className $fruitsArrayObject->getIteratorClass();
var_dump($className);

// Set new classname
$fruitsArrayObject->setIteratorClass('MyArrayIterator');

// Get the new iterator classname
$className $fruitsArrayObject->getIteratorClass();
var_dump($className);
?>

Il precedente esempio visualizzerà:

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

Vedere anche:



ArrayObject::ksort

(PHP 5 >= 5.2.0)

ArrayObject::ksortSort the entries by key

Descrizione

public void ArrayObject::ksort ( void )

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::ksort() example

<?php
$fruits 
= array("d" => "lemon""a" => "orange""b" => "banana""c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->ksort();

foreach (
$fruitArrayObject as $key => $val) {
    echo 
"$key = $val\n";
}
 
?>

Il precedente esempio visualizzerà:

a = orange
b = banana
c = apple
d = lemon

Vedere anche:



ArrayObject::natcasesort

(PHP 5 >= 5.2.0)

ArrayObject::natcasesortSort an array using a case insensitive "natural order" algorithm

Descrizione

public void ArrayObject::natcasesort ( void )

This method is a case insensitive version of ArrayObject::natsort.

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::natcasesort() example

<?php
$array 
= array('IMG0.png''img12.png''img10.png''img2.png''img1.png''IMG3.png');

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo 
"Standard sorting\n";
print_r($arr1);

$arr2->natcasesort();
echo 
"\nNatural order sorting (case-insensitive)\n";
print_r($arr2);
?>

Il precedente esempio visualizzerà:

Standard sorting
ArrayObject Object
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [2] => img10.png
    [1] => img12.png
    [3] => img2.png
)

Natural order sorting (case-insensitive)
ArrayObject Object
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Vedere anche:



ArrayObject::natsort

(PHP 5 >= 5.2.0)

ArrayObject::natsortSort entries using a "natural order" algorithm

Descrizione

public void ArrayObject::natsort ( void )

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) method can be seen in the example below.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::natsort() example

<?php
$array 
= array("img12.png""img10.png""img2.png""img1.png");

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo 
"Standard sorting\n";
print_r($arr1);

$arr2->natsort();
echo 
"\nNatural order sorting\n";
print_r($arr2);
?>

Il precedente esempio visualizzerà:

Standard sorting
ArrayObject Object
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
ArrayObject Object
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Vedere anche:



ArrayObject::offsetExists

(PHP 5 >= 5.0.0)

ArrayObject::offsetExistsReturns whether the requested index exists

Descrizione

public bool ArrayObject::offsetExists ( mixed $index )

Elenco dei parametri

index

The index being checked.

Valori restituiti

TRUE if the requested index exists, otherwise FALSE

Esempi

Example #1 ArrayObject::offsetExists() example

<?php
$arrayobj 
= new ArrayObject(array('zero''one''example'=>'e.g.'));
var_dump($arrayobj->offsetExists(1));
var_dump($arrayobj->offsetExists('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

Il precedente esempio visualizzerà:

bool(true)
bool(true)
bool(false)



ArrayObject::offsetGet

(PHP 5 >= 5.0.0)

ArrayObject::offsetGetReturns the value at the specified index

Descrizione

public mixed ArrayObject::offsetGet ( mixed $index )

Elenco dei parametri

index

The index with the value.

Valori restituiti

The value at the specified index or NULL.

Errori/Eccezioni

Produces an E_NOTICE error message when the specified index does not exist.

Esempi

Example #1 ArrayObject::offsetGet() example

<?php
$arrayobj 
= new ArrayObject(array('zero'7'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

Il precedente esempio visualizzerà:

int(7)
string(4) "e.g."
bool(false)



ArrayObject::offsetSet

(PHP 5 >= 5.0.0)

ArrayObject::offsetSetSets the value at the specified index to newval

Descrizione

public void ArrayObject::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Elenco dei parametri

index

The index being set.

newval

The new value for the index.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::offsetSet() example

<?php
class Example {
    public 
$property 'prop:public';
}
$arrayobj = new ArrayObject(new Example());
$arrayobj->offsetSet(4'four');
$arrayobj->offsetSet('group', array('g1''g2'));
var_dump($arrayobj);

$arrayobj = new ArrayObject(array('zero','one'));
$arrayobj->offsetSet(null'last');
var_dump($arrayobj);
?>

Il precedente esempio visualizzerà:

object(ArrayObject)#1 (3) {
  ["property"]=>
  string(11) "prop:public"
  [4]=>
  string(4) "four"
  ["group"]=>
  array(2) {
    [0]=>
    string(2) "g1"
    [1]=>
    string(2) "g2"
  }
}
object(ArrayObject)#3 (3) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(4) "last"
}

Vedere anche:



ArrayObject::offsetUnset

(PHP 5 >= 5.0.0)

ArrayObject::offsetUnsetUnsets the value at the specified index

Descrizione

public void ArrayObject::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Elenco dei parametri

index

The index being unset.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::offsetUnset() example

<?php
$arrayobj 
= new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

Il precedente esempio visualizzerà:

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}



ArrayObject::serialize

(PHP 5 >= 5.3.0)

ArrayObject::serializeSerialize an ArrayObject

Descrizione

public string ArrayObject::serialize ( void )

Serializes an ArrayObject.

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

The serialized representation of the ArrayObject.

Esempi

Example #1 ArrayObject::serialize() example

<?php
$o 
= new ArrayObject();

$s1 serialize($o);
$s2 $o->serialize();

var_dump($s1);
var_dump($s2);
?>

Il precedente esempio visualizzerà:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

Vedere anche:



ArrayObject::setFlags

(PHP 5 >= 5.1.0)

ArrayObject::setFlagsSets the behavior flags.

Descrizione

public void ArrayObject::setFlags ( int $flags )

Set the flags that change the behavior of the ArrayObject.

Elenco dei parametri

flags

The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayObject behavior flags
value constant
1 ArrayObject::STD_PROP_LIST
2 ArrayObject::ARRAY_AS_PROPS

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::setFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Try to use array key as property
var_dump($fruitsArrayObject->lemons);
// Set the flag so that the array keys can be used as properties of the ArrayObject
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);
// Try it again
var_dump($fruitsArrayObject->lemons);
?>

Il precedente esempio visualizzerà:

NULL
int(1)



ArrayObject::setIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::setIteratorClassSets the iterator classname for the ArrayObject.

Descrizione

public void ArrayObject::setIteratorClass ( string $iterator_class )

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

Elenco dei parametri

iterator_class

The classname of the array iterator to use when iterating over this object.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::setIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    
// custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1"oranges" => 4"bananas" => 5"apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Set the iterator classname to the newly
$fruitsArrayObject->setIteratorClass('MyArrayIterator');
print_r($fruitsArrayObject->getIterator());

?>

Il precedente esempio visualizzerà:

MyArrayIterator Object
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)



ArrayObject::uasort

(PHP 5 >= 5.2.0)

ArrayObject::uasortSort the entries with a user-defined comparison function and maintain key association

Descrizione

public void ArrayObject::uasort ( callable $cmp_function )

This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Elenco dei parametri

cmp_function

Function cmp_function should accept two parameters which will be filled by pairs of entries. 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.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::uasort() example

<?php
// Comparison function
function cmp($a$b) {
    if (
$a == $b) {
        return 
0;
    }
    return (
$a $b) ? -1;
}

// Array to be sorted
$array = array('a' => 4'b' => 8'c' => -1'd' => -9'e' => 2'f' => 5'g' => 3'h' => -4);
$arrayObject = new ArrayObject($array);
print_r($arrayObject);

// Sort and print the resulting array
$arrayObject->uasort('cmp');
print_r($arrayObject);
?>

Il precedente esempio visualizzerà:

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
)

Vedere anche:



ArrayObject::uksort

(PHP 5 >= 5.2.0)

ArrayObject::uksortSort the entries by keys using a user-defined comparison function

Descrizione

public void ArrayObject::uksort ( callable $cmp_function )

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Elenco dei parametri

cmp_function

The callback comparison function.

Function cmp_function should accept two parameters which will be filled by pairs of entry keys. 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.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 ArrayObject::uksort() example

<?php
function cmp($a$b) {
    
$a preg_replace('@^(a|an|the) @'''$a);
    
$b preg_replace('@^(a|an|the) @'''$b);
    return 
strcasecmp($a$b);
}

$array = array("John" => 1"the Earth" => 2"an apple" => 3"a banana" => 4);
$arrayObject = new ArrayObject($array);
$arrayObject->uksort('cmp');

foreach (
$arrayObject as $key => $value) {
    echo 
"$key$value\n";
}
?>

Il precedente esempio visualizzerà:

an apple: 3
a banana: 4
the Earth: 2
John: 1

Vedere anche:



ArrayObject::unserialize

(PHP 5 >= 5.3.0)

ArrayObject::unserializeUnserialize an ArrayObject

Descrizione

public void ArrayObject::unserialize ( string $serialized )

Unserializes a serialized ArrayObject.

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

serialized

The serialized ArrayObject.

Valori restituiti

The unserialized ArrayObject.

Vedere anche:


Indice dei contenuti



The SplObserver interface

(PHP 5 >= 5.1.0)

Introduzione

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

Sommario dell'interfaccia

SplObserver {
/* Metodi */
abstract public void update ( SplSubject $subject )
}

SplObserver::update

(PHP 5 >= 5.1.0)

SplObserver::updateReceive update from subject

Descrizione

abstract public void SplObserver::update ( SplSubject $subject )

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

subject

The SplSubject notifying the observer of an update.

Valori restituiti

Nessun valore viene restituito.


Indice dei contenuti



The SplSubject interface

(PHP 5 >= 5.1.0)

Introduzione

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

Sommario dell'interfaccia

SplSubject {
/* Metodi */
abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )
}

SplSubject::attach

(PHP 5 >= 5.1.0)

SplSubject::attachAttach an SplObserver

Descrizione

abstract public void SplSubject::attach ( SplObserver $observer )

Attaches an SplObserver so that it can be notified of updates.

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

observer

The SplObserver to attach.

Valori restituiti

Nessun valore viene restituito.



SplSubject::detach

(PHP 5 >= 5.1.0)

SplSubject::detachDetach an observer

Descrizione

abstract public void SplSubject::detach ( SplObserver $observer )

Detaches an observer from the subject to no longer notify it of updates.

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

observer

The SplObserver to detach.

Valori restituiti

Nessun valore viene restituito.



SplSubject::notify

(PHP 5 >= 5.1.0)

SplSubject::notifyNotify an observer

Descrizione

abstract public void SplSubject::notify ( void )

Notifies all attached observers.

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.


Indice dei contenuti





SPL Type Handling


Introduzione

This extension aims at helping people making PHP a stronger typed language and can be a good alternative to scalar type hinting. It provides different typehandling classes as such as integer, float, bool, enum and string

Avviso

Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio.



Installazione/Configurazione

Indice dei contenuti


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.



Installazione

Questa estensione » PECL non è incorporata nel PHP.

Informazioni per l'installazione di questa estensione PECL possono essere trovate nel capitolo del manuale intitolato Installazione delle estensioni PECL. Informazioni aggiuntive come nuove release, download, file sorgenti, informazioni del manutentore e un CHANGELOG possono essere trovate qui: » http://pecl.php.net/package/SPL_Types.

La DLL per questa estensione PECL non è attualmente disponibile. Vedere la sezione compilazione su Windows



Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini



Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.




The SplType class

(PECL spl_types >= 0.1.0)

Introduzione

Parent class for all SPL types.

Sommario dellla classe

abstract SplType {
/* Constants */
const NULL __default = null ;
/* Metodi */
__construct ([ mixed $initial_value [, bool $strict ]] )
}

Costanti predefinite

SplType::__default


SplType::__construct

(PECL spl_types >= 0.1.0)

SplType::__constructCreates a new value of some type

Descrizione

SplType::__construct ([ mixed $initial_value [, bool $strict ]] )

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

initial_value

Type and default value depends on the extension class.

strict

Whether to set the object's sctrictness.

Errori/Eccezioni

Throws an UnexpectedValueException if incompatible type is given.


Indice dei contenuti



The SplInt class

(PECL spl_types >= 0.1.0)

Introduzione

The SplInt class is used to enforce strong typing of the integer type.

Sommario dellla classe

SplInt extends SplType {
/* Constants */
const integer __default = 0 ;
/* Metodi ereditati */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Costanti predefinite

SplInt::__default

Esempi

Example #1 SplInt usage example

<?php
$int 
= new SplInt(94);

try {
    
$int 'Try to cast a string value for fun';
} catch (
UnexpectedValueException $uve) {
    echo 
$uve->getMessage() . PHP_EOL;
}

echo 
$int PHP_EOL;
?>

Il precedente esempio visualizzerà:

Value not an integer
94



The SplFloat class

(PECL spl_types >= 0.1.0)

Introduzione

The SplFloat class is used to enforce strong typing of the float type.

Sommario dellla classe

SplFloat extends SplType {
/* Constants */
const float __default = 0 ;
/* Metodi ereditati */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Costanti predefinite

SplFloat::__default

Esempi

Example #1 SplFloat usage example

<?php
$float 
= new SplFloat(3.154);
$newFloat = new SplFloat(3);

try {
    
$float 'Try to cast a string value for fun';
} catch (
UnexpectedValueException $uve) {
    echo 
$uve->getMessage() . PHP_EOL;
}

echo 
$float PHP_EOL;
echo 
$newFloat PHP_EOL;
?>

Il precedente esempio visualizzerà:

Value not a float
3.154
3



The SplEnum class

(PECL spl_types >= 0.1.0)

Introduzione

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Sommario dellla classe

SplEnum extends SplType {
/* Constants */
const NULL __default = null ;
/* Metodi */
public array getConstList ([ bool $include_default = false ] )
/* Metodi ereditati */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Costanti predefinite

SplEnum::__default

Esempi

Example #1 SplEnum usage example

<?php
class Month extends SplEnum {
    const 
__default self::January;
    
    const 
January 1;
    const 
February 2;
    const 
March 3;
    const 
April 4;
    const 
May 5;
    const 
June 6;
    const 
July 7;
    const 
August 8;
    const 
September 9;
    const 
October 10;
    const 
November 11;
    const 
December 12;
}

echo new 
Month(Month::June) . PHP_EOL;

try {
    new 
Month(13);
} catch (
UnexpectedValueException $uve) {
    echo 
$uve->getMessage() . PHP_EOL;
}
?>

Il precedente esempio visualizzerà:

6
Value not a const in enum Month


SplEnum::getConstList

(PECL spl_types >= 0.1.0)

SplEnum::getConstListReturns all consts (possible values) as an array.

Descrizione

public array SplEnum::getConstList ([ bool $include_default = false ] )

Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

include_default

Whether to include __default property.

Valori restituiti

Esempi

Example #1 SplEnum::getConstList() example

<?php
$bool 
= new SplBool;
var_dump($bool->getConstList(true));
?>

Il precedente esempio visualizzerà:

array(3) {
  ["__default"]=>
  bool(false)
  ["false"]=>
  bool(false)
  ["true"]=>
  bool(true)
}


Indice dei contenuti



The SplBool class

(PECL spl_types >= 0.1.0)

Introduzione

The SplBool class is used to enforce strong typing of the bool type.

Sommario dellla classe

SplBool extends SplEnum {
/* Constants */
const boolean __default = false ;
const boolean false = false ;
const boolean true = true ;
/* Metodi ereditati */
public array SplEnum::getConstList ([ bool $include_default = false ] )
}

Costanti predefinite

SplBool::__default

SplBool::false

SplBool::true

Esempi

Example #1 SplBool usage example

<?php
$true 
= new SplBool(true);
if (
$true) {
    echo 
"TRUE\n";
}

$false = new SplBool;
if (
$false) {
    echo 
"FALSE\n";
}
?>

Il precedente esempio visualizzerà:

TRUE



The SplString class

(PECL spl_types >= 0.1.0)

Introduzione

The SplString class is used to enforce strong typing of the string type.

Sommario dellla classe

SplString extends SplType {
/* Constants */
const integer __default = 0 ;
/* Metodi ereditati */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Costanti predefinite

SplString::__default

Esempi

Example #1 SplString usage example

<?php
$string 
= new SplString("Testing");

try {
    
$string = array();
} catch (
UnexpectedValueException $uve) {
    echo 
$uve->getMessage() . PHP_EOL;
}

var_dump($string);
echo 
$string// Outputs "Testing"
?>

Il precedente esempio visualizzerà:

Value not a string
object(SplString)#1 (1) {
  ["__default"]=>
  string(7) "Testing"
}
Testing




Streams


Introduzione

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Supported Protocols and Wrappers), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Working with streams. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Supported Protocols and Wrappers for a list of PHP built-in wrappers. If no wrapper is specified, the function default is used (typically file://).
  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Supported Protocols and Wrappers for a description of targets for built-in streams.

Nota:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.



Installazione/Configurazione

Indice dei contenuti


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.



Installazione

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.



Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini



Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

Class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.




Costanti predefinite

Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.

Constant Description
STREAM_FILTER_READ * Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE * Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL * This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON * Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME * Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL * Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
PSFS_FLAG_NORMAL Regular read/write.
PSFS_FLAG_FLUSH_INC An incremental flush.
PSFS_FLAG_FLUSH_CLOSE Final flush prior to closing.
STREAM_USE_PATH Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT * Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT * Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT * Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND * Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN * Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE * A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED * There is no more data available on the stream.
STREAM_NOTIFY_FAILURE A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + Provides a ICMP socket.
STREAM_IPPROTO_IP + Provides a IP socket.
STREAM_IPPROTO_RAW + Provides a RAW socket.
STREAM_IPPROTO_TCP + Provides a TCP socket.
STREAM_IPPROTO_UDP + Provides a UDP socket.
STREAM_PF_INET + Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + Unix system internal protocols.
STREAM_SOCK_DGRAM + Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD Used with stream_socket_shutdown() to disable further receptions. Added in PHP 5.2.1.
STREAM_SHUT_WR Used with stream_socket_shutdown() to disable further transmissions. Added in PHP 5.2.1.
STREAM_SHUT_RDWR Used with stream_socket_shutdown() to disable further receptions and transmissions. Added in PHP 5.2.1.
STREAM_CAST_FOR_SELECT Stream casting, for when stream_select() is calling stream_cast().
STREAM_CAST_AS_STREAM Stream casting, when stream_cast() is called otherwise (see above).
STREAM_META_TOUCH Used with stream_metadata(), to specify touch() call.
STREAM_META_OWNER Used with stream_metadata(), to specify chown() call.
STREAM_META_OWNER_NAME Used with stream_metadata(), to specify chown() call.
STREAM_META_GROUP Used with stream_metadata(), to specify chgrp() call.
STREAM_META_GROUP_NAME Used with stream_metadata(), to specify chgrp() call.
STREAM_META_ACCESS Used with stream_metadata(), to specify chmod() call.

Nota: The constants marked with * are just available since PHP 5.0.0.

Nota: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Nota: The STREAM_META_* constants are available since PHP 5.4.0 and are meant to be used with stream_metadata().



Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Working with streams. To access the list of currently registered filters, use stream_get_filters().



Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found in the Context options and parameters chapter.

Parameters can be specified for contexts using the stream_context_set_params() function.



Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.



Esempi

Indice dei contenuti

Example #1 Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

Example #2 Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
* Include form elements named "foo" and "bar" with dummy values
*/

$sock fsockopen("ssl://secure.example.com"443$errno$errstr30);
if (!
$sock) die("$errstr ($errno)\n");

$data "foo=" urlencode("Value for Foo") . "&bar=" urlencode("Value for Bar");

fwrite($sock"POST /form_action.php HTTP/1.0\r\n");
fwrite($sock"Host: secure.example.com\r\n");
fwrite($sock"Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock"Content-length: " strlen($data) . "\r\n");
fwrite($sock"Accept: */*\r\n");
fwrite($sock"\r\n");
fwrite($sock$data);

$headers "";
while (
$str trim(fgets($sock4096)))
$headers .= "$str\n";

echo 
"\n";

$body "";
while (!
feof($sock))
$body .= fgets($sock4096);

fclose($sock);
?>

Example #3 Writing data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
* File can be read back using compress.zlib stream or just
* decompressed from the command line using 'gzip -d foo-bar.txt.gz'
*/
$fp fopen("compress.zlib://foo-bar.txt.gz""wb");
if (!
$fp) die("Unable to create file.");

fwrite($fp"This is a test.\n");

fclose($fp);
?>


Example class registered as stream wrapper

The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].

Example #1 A Stream for reading/writing global variables

<?php

class VariableStream {
    var 
$position;
    var 
$varname;

    function 
stream_open($path$mode$options, &$opened_path)
    {
        
$url parse_url($path);
        
$this->varname $url["host"];
        
$this->position 0;

        return 
true;
    }

    function 
stream_read($count)
    {
        
$ret substr($GLOBALS[$this->varname], $this->position$count);
        
$this->position += strlen($ret);
        return 
$ret;
    }

    function 
stream_write($data)
    {
        
$left substr($GLOBALS[$this->varname], 0$this->position);
        
$right substr($GLOBALS[$this->varname], $this->position strlen($data));
        
$GLOBALS[$this->varname] = $left $data $right;
        
$this->position += strlen($data);
        return 
strlen($data);
    }

    function 
stream_tell()
    {
        return 
$this->position;
    }

    function 
stream_eof()
    {
        return 
$this->position >= strlen($GLOBALS[$this->varname]);
    }

    function 
stream_seek($offset$whence)
    {
        switch (
$whence) {
            case 
SEEK_SET:
                if (
$offset strlen($GLOBALS[$this->varname]) && $offset >= 0) {
                     
$this->position $offset;
                     return 
true;
                } else {
                     return 
false;
                }
                break;

            case 
SEEK_CUR:
                if (
$offset >= 0) {
                     
$this->position += $offset;
                     return 
true;
                } else {
                     return 
false;
                }
                break;

            case 
SEEK_END:
                if (
strlen($GLOBALS[$this->varname]) + $offset >= 0) {
                     
$this->position strlen($GLOBALS[$this->varname]) + $offset;
                     return 
true;
                } else {
                     return 
false;
                }
                break;

            default:
                return 
false;
        }
    }

    function 
stream_metadata($path$option$var
    {
        if(
$option == STREAM_META_TOUCH) {
            
$url parse_url($path);
            
$varname $url["host"];
            if(!isset(
$GLOBALS[$varname])) {
                
$GLOBALS[$varname] = '';
            }
            return 
true;
        }
        return 
false;
    }
}

stream_wrapper_register("var""VariableStream")
    or die(
"Failed to register protocol");

$myvar "";

$fp fopen("var://myvar""r+");

fwrite($fp"line1\n");
fwrite($fp"line2\n");
fwrite($fp"line3\n");

rewind($fp);
while (!
feof($fp)) {
    echo 
fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

Il precedente esempio visualizzerà:

line1
line2
line3
string(18) "line1
line2
line3
"




The php_user_filter class

(PHP 5)

Introduzione

Children of this class are passed to stream_filter_register().

Sommario dellla classe

php_user_filter {
/* Proprietà */
public $filtername ;
public $params ;
/* Metodi */
public int filter ( resource $in , resource $out , int &$consumed , bool $closing )
public void onClose ( void )
public bool onCreate ( void )
}

Proprietà

filtername

Name of the filter registered by stream_filter_append().

params


php_user_filter::filter

(PHP 5)

php_user_filter::filterCalled when applying the filter

Descrizione

public int php_user_filter::filter ( resource $in , resource $out , int &$consumed , bool $closing )

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()).

Elenco dei parametri

in

in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out

out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed

consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket.

closing

If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE.

Valori restituiti

The filter() method must return one of three values upon completion.

Return Value Meaning
PSFS_PASS_ON Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) The filter experienced an unrecoverable error and cannot continue.



php_user_filter::onClose

(PHP 5)

php_user_filter::onCloseCalled when closing the filter

Descrizione

public void php_user_filter::onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Return value is ignored.



php_user_filter::onCreate

(PHP 5)

php_user_filter::onCreateCalled when creating the filter

Descrizione

public bool php_user_filter::onCreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property Contents
FilterClass->filtername A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to FALSE.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Your implementation of this method should return FALSE on failure, or TRUE on success.


Indice dei contenuti



The streamWrapper class

(PHP 4 >= 4.3.2, PHP 5)

Introduzione

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Nota:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Nota:

Implementing the methods in other ways then described here can lead to undefined behaviour.

An instance of this class is initialized as soon as a stream function tries to access the protocol it is associated with.

Sommario dellla classe

streamWrapper {
/* Proprietà */
public resource $context ;
/* Metodi */
__construct ( void )
__destruct ( void )
public bool dir_closedir ( void )
public bool dir_opendir ( string $path , int $options )
public string dir_readdir ( void )
public bool dir_rewinddir ( void )
public bool mkdir ( string $path , int $mode , int $options )
public bool rename ( string $path_from , string $path_to )
public bool rmdir ( string $path , int $options )
public resource stream_cast ( int $cast_as )
public void stream_close ( void )
public bool stream_eof ( void )
public bool stream_flush ( void )
public bool stream_lock ( int $operation )
public bool stream_metadata ( string $path , int $option , mixed $value )
public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )
public string stream_read ( int $count )
public bool stream_seek ( int $offset , int $whence = SEEK_SET )
public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
public array stream_stat ( void )
public int stream_tell ( void )
public bool stream_truncate ( int $new_size )
public int stream_write ( string $data )
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}

Proprietà

resource context

The current context, or NULL if no context was passed to the caller function.

Use the stream_context_get_options() to parse the context.

Nota:

This property must be public so PHP can populate it with the actual context resource.

Log delle modifiche

Versione Descrizione
5.0.0 Added the context property.


streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::__constructConstructs a new stream wrapper

Descrizione

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open().

Elenco dei parametri

Questa funzione non contiene parametri.



streamWrapper::__destruct

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::__destructDestructs an existing stream wrapper

Descrizione

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

Elenco dei parametri

Questa funzione non contiene parametri.



streamWrapper::dir_closedir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_closedirClose directory handle

Descrizione

public bool streamWrapper::dir_closedir ( void )

This method is called in response to closedir().

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:



streamWrapper::dir_opendir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_opendirOpen directory handle

Descrizione

public bool streamWrapper::dir_opendir ( string $path , int $options )

This method is called in response to opendir().

Elenco dei parametri

path

Specifies the URL that was passed to opendir().

Nota:

The URL can be broken apart with parse_url().

options

Whether or not to enforce safe_mode (0x04).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:



streamWrapper::dir_readdir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_readdirRead entry from directory handle

Descrizione

public string streamWrapper::dir_readdir ( void )

This method is called in response to readdir().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Should return string representing the next filename, or FALSE if there is no next file.

Nota:

The return value will be casted to string.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Esempi

Example #1 Listing files from tar archives

<?php
class streamWrapper {
    protected 
$fp;

    public function 
dir_opendir($path$options) {
        
$url parse_url($path);

        
$path $url["host"] . $url["path"];

        if (!
is_readable($path)) {
            
trigger_error("$path isn't readable for me"E_USER_NOTICE);
            return 
false;
        }
        if (!
is_file($path)) {
            
trigger_error("$path isn't a file"E_USER_NOTICE);
            return 
false;
        }

        
$this->fp fopen($path"rb");
        return 
true;
    }

    public function 
dir_readdir() {
        
// Extract the header for this entry
        
$header      fread($this->fp512);
        
$data unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile"$header);

        
// Trim the filename and filesize
        
$filename    trim($data["filename"]);

        
// No filename? We are the end of the archive
        
if (!$filename) {
            return 
false;
        }

        
$octal_bytes trim($data["size"]);
        
// Filesize is defined in octects
        
$bytes       octdec($octal_bytes);

        
// tar rounds up filesizes up to multiple of 512 bytes (zero filled)
        
$rest        $bytes 512;
        if (
$rest 0) {
            
$bytes      += 512 $rest;
        }

        
// Seek over the file
        
fseek($this->fp$bytesSEEK_CUR);

        return 
$filename;
    }

    public function 
dir_closedir() {
        return 
fclose($this->fp);
    }

    public function 
dir_rewinddir() {
        return 
fseek($this->fp0SEEK_SET);
    }
}

stream_wrapper_register("tar""streamWrapper");
$handle opendir("tar://example.tar");
while (
false !== ($file readdir($handle))) {
    
var_dump($file);
}

echo 
"Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

Vedere anche:

  • readdir() - Legge una voce dall'handle della directory



streamWrapper::dir_rewinddir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_rewinddirRewind directory handle

Descrizione

public bool streamWrapper::dir_rewinddir ( void )

This method is called in response to rewinddir().

Should reset the output generated by streamWrapper::dir_readdir(). i.e.: The next call to streamWrapper::dir_readdir() should return the first entry in the location returned by streamWrapper::dir_opendir().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:



streamWrapper::mkdir

(PHP 5)

streamWrapper::mkdirCreate a directory

Descrizione

public bool streamWrapper::mkdir ( string $path , int $mode , int $options )

This method is called in response to mkdir().

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

Elenco dei parametri

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note

Nota:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

Vedere anche:



streamWrapper::rename

(PHP 5)

streamWrapper::renameRenames a file or directory

Descrizione

public bool streamWrapper::rename ( string $path_from , string $path_to )

This method is called in response to rename().

Should attempt to rename path_from to path_to

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

Elenco dei parametri

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note

Nota:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

Vedere anche:

  • rename() - Rinomina un file o una directory



streamWrapper::rmdir

(PHP 5)

streamWrapper::rmdirRemoves a directory

Descrizione

public bool streamWrapper::rmdir ( string $path , int $options )

This method is called in response to rmdir().

Nota:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

Elenco dei parametri

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note

Nota:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

Vedere anche:



streamWrapper::stream_cast

(PHP 5 >= 5.3.0)

streamWrapper::stream_castRetrieve the underlaying resource

Descrizione

public resource streamWrapper::stream_cast ( int $cast_as )

This method is called in response to stream_select().

Elenco dei parametri

cast_as

Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses.

Valori restituiti

Should return the underlying stream resource used by the wrapper, or FALSE.

Vedere anche:

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec



streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_closeClose an resource

Descrizione

public void streamWrapper::stream_close ( void )

This method is called in response to fclose().

All resources that were locked, or allocated, by the wrapper should be released.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Nessun valore viene restituito.

Vedere anche:



streamWrapper::stream_eof

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_eofTests for end-of-file on a file pointer

Descrizione

public bool streamWrapper::stream_eof ( void )

This method is called in response to feof().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

Note

Avviso

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

Vedere anche:

  • feof() - Verifica se è stata raggiunta la fine del file su un puntatore a file



streamWrapper::stream_flush

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_flushFlushes the output

Descrizione

public bool streamWrapper::stream_flush ( void )

This method is called in response to fflush().

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Should return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

Note

Nota:

If not implemented, FALSE is assumed as the return value.

Vedere anche:



streamWrapper::stream_lock

(PHP 5)

streamWrapper::stream_lockAdvisory file locking

Descrizione

public bool streamWrapper::stream_lock ( int $operation )

This method is called in response to flock(), when file_put_contents() (when flags contains LOCK_EX), stream_set_blocking() and when closing the stream (LOCK_UN).

Elenco dei parametri

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock() to block while locking. (not supported on Windows)

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Vedere anche:



streamWrapper::stream_metadata

(PHP 5 >= 5.4.0)

streamWrapper::stream_metadataChange stream options

Descrizione

public bool streamWrapper::stream_metadata ( string $path , int $option , mixed $value )

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

Please note that some of these operations may not be available on your system.

Nota: The function is available since PHP 5.4.0.

Elenco dei parametri

path

The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option

One of:

  • STREAM_META_TOUCH (The method was called in response to touch())
  • STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown())
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • STREAM_META_GROUP (The method was called in response to chgrp())
  • STREAM_META_ACCESS (The method was called in response to chmod())

value

If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as integer.
  • STREAM_META_ACCESS: The argument of the chmod() as integer.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If option is not implemented, FALSE should be returned.

Vedere anche:

  • touch() - Imposta l'ora di modifica di un file
  • chmod() - Cambia le impostazioni del file
  • chown() - Cambia il proprietario del file
  • chgrp() - Cambia il gruppo del file



streamWrapper::stream_open

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_openOpens file or URL

Descrizione

public bool streamWrapper::stream_open ( string $path , string $mode , int $options , string &$opened_path )

This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).

Elenco dei parametri

path

Specifies the URL that was passed to the original function.

Nota:

The URL can be broken apart with parse_url(). Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode

The mode used to open the file, as detailed for fopen().

Nota:

Remember to check if the mode is valid for the path requested.

options

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag Description
STREAM_USE_PATH If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path

If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note

Nota:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

Vedere anche:



streamWrapper::stream_read

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_readRead from stream

Descrizione

public string streamWrapper::stream_read ( int $count )

This method is called in response to fread() and fgets().

Nota:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

Elenco dei parametri

count

How many bytes of data from the current position should be returned.

Valori restituiti

If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Nota:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

Note

Nota:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Avviso

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

Vedere anche:

  • fread() - Legge un file salvaguardando la corrispondenza binaria
  • fgets() - Prende una riga da un puntatore a file



streamWrapper::stream_seek

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_seekSeeks to specific location in a stream

Descrizione

public bool streamWrapper::stream_seek ( int $offset , int $whence = SEEK_SET )

This method is called in response to fseek().

The read/write position of the stream should be updated according to the offset and whence.

Elenco dei parametri

offset

The stream offset to seek to.

whence

Possible values:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Valori restituiti

Return TRUE if the position was updated, FALSE otherwise.

Note

Nota:

If not implemented, FALSE is assumed as the return value.

Nota:

Upon success, streamWrapper::stream_tell() is called directly after calling streamWrapper::stream_seek(). If streamWrapper::stream_tell() fails, the return value to the caller function will be set to FALSE

Nota:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer()) and seeking may be done by merely moving the buffer pointer.

Vedere anche:

  • fseek() - Sposta un puntatore sul file



streamWrapper::stream_set_option

(PHP 5 >= 5.3.0)

streamWrapper::stream_set_optionChange stream options

Descrizione

public bool streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 )

This method is called to set options on the stream.

Elenco dei parametri

option

One of:

arg1

If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2

If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If option is not implemented, FALSE should be returned.

Vedere anche:



streamWrapper::stream_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_statRetrieve information about a file resource

Descrizione

public array streamWrapper::stream_stat ( void )

This method is called in response to fstat().

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

See stat().

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Vedere anche:



streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_tellRetrieve the current position of a stream

Descrizione

public int streamWrapper::stream_tell ( void )

This method is called in response to fseek() to determine the current position.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Should return the current position of the stream.

Vedere anche:

  • streamWrapper::stream_tell()



streamWrapper::stream_truncate

(PHP 5 >= 5.4.0)

streamWrapper::stream_truncateTruncate stream

Descrizione

public bool streamWrapper::stream_truncate ( int $new_size )

Will respond to truncation, e.g., through ftruncate().

Elenco dei parametri

new_size

The new size.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:



streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_writeWrite to stream

Descrizione

public int streamWrapper::stream_write ( string $data )

This method is called in response to fwrite().

Nota:

Remember to update the current position of the stream by number of bytes that were successfully written.

Elenco dei parametri

data

Should be stored into the underlying stream.

Nota:

If there is not enough room in the underlying stream, store as much as possible.

Valori restituiti

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Nota:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

Vedere anche:

  • fwrite() - Scrive un file salvaguardando la corrispondenza binaria




streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::url_statRetrieve information about a file

Elenco dei parametri

path

The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag Description
STREAM_URL_STAT_LINK For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

Valori restituiti

Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0).

Errori/Eccezioni

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note

Nota:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

Vedere anche:


Indice dei contenuti



Stream Funzioni


set_socket_blocking

(PHP 4, PHP 5)

set_socket_blockingAlias di stream_set_blocking()

Descrizione

Questa funzione è sinonimo di: stream_set_blocking()

Avviso

Questa funzionalità è DEPRECATA dal PHP 5.3.0. Fare affidamento su questa funzionalità è altamente sconsigliato.



stream_bucket_append

(PHP 5)

stream_bucket_append Append bucket to brigade

Descrizione

void stream_bucket_append ( resource $brigade , resource $bucket )
Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.



stream_bucket_make_writeable

(PHP 5)

stream_bucket_make_writeable Return a bucket object from the brigade for operating on

Descrizione

object stream_bucket_make_writeable ( resource $brigade )
Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.



stream_bucket_new

(PHP 5)

stream_bucket_new Create a new bucket for use on the current stream

Descrizione

object stream_bucket_new ( resource $stream , string $buffer )
Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.



stream_bucket_prepend

(PHP 5)

stream_bucket_prepend Prepend bucket to brigade

Descrizione

void stream_bucket_prepend ( resource $brigade , resource $bucket )

This function can be called to prepend a bucket to a bucket brigade. It is typically called from php_user_filter::filter().

Elenco dei parametri

brigade

brigade is a resource pointing to a bucket brigade which contains one or more bucket objects.

bucket

A bucket object.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 stream_bucket_prepend() examples

<?php

class foo extends php_user_filter {
  protected 
$calls 0;
  public function 
filter($in$out, &$consumed$closing) {
    while (
$bucket stream_bucket_make_writeable($in)) {
      
$consumed += $bucket->datalen;
      if (
$this->calls++ == 2) {
        
// This bucket will appear again before any other bucket.
        
stream_bucket_prepend($in$bucket);
      }
    }
    return 
PSFS_FEED_ME;
  }
}
stream_filter_register('test''foo');
print  
file_get_contents('php://filter/read=test/resource=foo');
?>



stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_createCreates a stream context

Descrizione

resource stream_context_create ([ array $options [, array $params ]] )

Creates and returns a stream context with any options supplied in options preset.

Elenco dei parametri

options

Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Default to an empty array.

params

Must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.

Valori restituiti

A stream context resource.

Log delle modifiche

Versione Descrizione
5.3.0 Added the optional params argument.

Esempi

Example #1 Using stream_context_create()

<?php
$opts 
= array(
  
'http'=>array(
    
'method'=>"GET",
    
'header'=>"Accept-language: en\r\n" .
              
"Cookie: foo=bar\r\n"
  
)
);

$context stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp fopen('http://www.example.com''r'false$context);
fpassthru($fp);
fclose($fp);
?>

Vedere anche:



stream_context_get_default

(PHP 5 >= 5.1.0)

stream_context_get_defaultRetrieve the default stream context

Descrizione

resource stream_context_get_default ([ array $options ] )

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

Elenco dei parametri

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Nota:

As of PHP 5.3.0, the stream_context_set_default() function can be used to set the default context.

Valori restituiti

A stream context resource.

Esempi

Example #1 Using stream_context_get_default()

<?php
$default_opts 
= array(
  
'http'=>array(
    
'method'=>"GET",
    
'header'=>"Accept-language: en\r\n" .
              
"Cookie: foo=bar",
    
'proxy'=>"tcp://10.54.1.39:8000"
  
)
);


$alternate_opts = array(
  
'http'=>array(
    
'method'=>"POST",
    
'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
              
"Content-length: " strlen("baz=bomb"),
    
'content'=>"baz=bomb"
  
)
);

$default stream_context_get_default($default_opts);
$alternate stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com'false$alternate);

?>

Vedere anche:



stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5)

stream_context_get_optionsRetrieve options for a stream/wrapper/context

Descrizione

array stream_context_get_options ( resource $stream_or_context )

Returns an array of options on the specified stream or context.

Elenco dei parametri

stream_or_context

The stream or context to get options from

Valori restituiti

Returns an associative array with the options.

Esempi

Example #1 stream_context_get_options() example

<?php
$params 
= array("method" => "POST");

stream_context_get_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

Il precedente esempio visualizzerà qualcosa simile a:

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}



stream_context_get_params

(PHP 5 >= 5.3.0)

stream_context_get_paramsRetrieves parameters from a context

Descrizione

array stream_context_get_params ( resource $stream_or_context )

Retrieves parameter and options information from the stream or context.

Elenco dei parametri

stream_or_context

A stream resource or a context resource

Valori restituiti

Returns an associate array containing all context options and parameters.

Esempi

Example #1 stream_context_get_params() example

Basic usage example

<?php
$ctx 
stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx$params);

var_dump(stream_context_get_params($ctx));
?>

Il precedente esempio visualizzerà qualcosa simile a:

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

Vedere anche:



stream_context_set_default

(PHP 5 >= 5.3.0)

stream_context_set_defaultSet the default stream context

Descrizione

resource stream_context_set_default ( array $options )

Set the default stream context which will be used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Uses the same syntax as stream_context_create().

Elenco dei parametri

options

The options to set for the default context.

Nota:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Valori restituiti

Returns the default stream context.

Esempi

Example #1 stream_context_set_default() example

<?php
$default_opts 
= array(
  
'http'=>array(
    
'method'=>"GET",
    
'header'=>"Accept-language: en\r\n" .
              
"Cookie: foo=bar",
    
'proxy'=>"tcp://10.54.1.39:8000"
  
)
);

$default stream_context_set_default($default_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');
?>

Vedere anche:



stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_optionSets an option for a stream/wrapper/context

Descrizione

bool stream_context_set_option ( resource $stream_or_context , string $wrapper , string $option , mixed $value )
bool stream_context_set_option ( resource $stream_or_context , array $options )

Sets an option on the specified context. value is set to option for wrapper

Elenco dei parametri

stream_or_context

The stream or context resource to apply the options to.

options

The options to set for the default context.

Nota:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Refer to context options and parameters for a listing of stream options.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.



stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_paramsSet parameters for a stream/wrapper/context

Descrizione

bool stream_context_set_params ( resource $stream_or_context , array $params )

Sets parameters on the specified context.

Elenco dei parametri

stream_or_context

The stream or context to apply the parameters too.

params

An array of parameters to set.

Nota:

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Supported parameters

Parameters Purpose
notification Name of user-defined callback function to be called whenever a stream triggers a notification.
options Array of options as in context options and parameters.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:



stream_copy_to_stream

(PHP 5)

stream_copy_to_streamCopies data from one stream to another

Descrizione

int stream_copy_to_stream ( resource $source , resource $dest [, int $maxlength = -1 [, int $offset = 0 ]] )

Makes a copy of up to maxlength bytes of data from the current position (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.

Elenco dei parametri

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Valori restituiti

Returns the total count of bytes copied.

Log delle modifiche

Versione Descrizione
5.1.0 Added the offset parameter

Esempi

Example #1 A stream_copy_to_stream() example

<?php
$src 
fopen('http://www.example.com''r');
$dest1 fopen('first1k.txt''w');
$dest2 fopen('remainder.txt''w');

echo 
stream_copy_to_stream($src$dest11024) . " bytes copied to first1k.txt\n";
echo 
stream_copy_to_stream($src$dest2) . " bytes copied to remainder.txt\n";

?>

Vedere anche:



stream_encoding

(No version information available, might only be in Git)

stream_encodingSet character set for stream encoding

Descrizione

bool stream_encoding ( resource $stream [, string $encoding ] )
Avviso

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.



stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_appendAttach a filter to a stream

Descrizione

resource stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Elenco dei parametri

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

params

This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

Valori restituiti

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Log delle modifiche

Versione Descrizione
5.1.0 Prior to PHP 5.1.0, this function returns TRUE on success o FALSE in caso di fallimento.

Esempi

Example #1 Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp fopen('test.txt''w+');

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp"string.rot13"STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp"This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?>

Note

Nota: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Nota: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

Vedere anche:



stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_prependAttach a filter to a stream

Descrizione

resource stream_filter_prepend ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Elenco dei parametri

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

params

This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

Valori restituiti

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Log delle modifiche

Versione Descrizione
5.1.0 Prior to PHP 5.1.0, this function returns TRUE on success o FALSE in caso di fallimento.

Note

Nota: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

Nota: When a filter is added for read and write, two instances of the filter are created. stream_filter_prepend() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

Vedere anche:



stream_filter_register

(PHP 5)

stream_filter_registerRegister a user defined stream filter

Descrizione

bool stream_filter_register ( string $filtername , string $classname )

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

Elenco dei parametri

filtername

The filter name to be registered.

classname

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described in php_user_filter - doing otherwise will lead to undefined behaviour.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

stream_filter_register() will return FALSE if the filtername is already defined.

Esempi

Example #1 Filter for capitalizing characters on foo-bar.txt stream

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function 
filter($in$out, &$consumed$closing)
  {
    while (
$bucket stream_bucket_make_writeable($in)) {
      
$bucket->data strtoupper($bucket->data);
      
$consumed += $bucket->datalen;
      
stream_bucket_append($out$bucket);
    }
    return 
PSFS_PASS_ON;
  }
}

/* Register our filter with PHP */
stream_filter_register("strtoupper""strtoupper_filter")
    or die(
"Failed to register filter");

$fp fopen("foo-bar.txt""w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp"strtoupper");

fwrite($fp"Line1\n");
fwrite($fp"Word - 2\n");
fwrite($fp"Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?>

Il precedente esempio visualizzerà:

LINE1
WORD - 2
EASY AS 123

Example #2 Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var 
$mode;

  function 
filter($in$out, &$consumed$closing)
  {
    while (
$bucket stream_bucket_make_writeable($in)) {
      if (
$this->mode == 1) {
        
$bucket->data strtoupper($bucket->data);
      } elseif (
$this->mode == 0) {
        
$bucket->data strtolower($bucket->data);
      }

      
$consumed += $bucket->datalen;
      
stream_bucket_append($out$bucket);
    }
    return 
PSFS_PASS_ON;
  }

  function 
onCreate()
  {
    if (
$this->filtername == 'str.toupper') {
      
$this->mode 1;
    } elseif (
$this->filtername == 'str.tolower') {
      
$this->mode 0;
    } else {
      
/* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      
return false;
    }

    return 
true;
  }
}

/* Register our filter with PHP */
stream_filter_register("str.*""string_filter")
    or die(
"Failed to register filter");

$fp fopen("foo-bar.txt""w");

/* Attach the registered filter to the stream just opened
   We could alternately bind to str.tolower here */
stream_filter_append($fp"str.toupper");

fwrite($fp"Line1\n");
fwrite($fp"Word - 2\n");
fwrite($fp"Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?>

Il precedente esempio visualizzerà:

LINE1
WORD - 2
EASY AS 123

Vedere anche:



stream_filter_remove

(PHP 5 >= 5.1.0)

stream_filter_removeRemove a filter from a stream

Descrizione

bool stream_filter_remove ( resource $stream_filter )

Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.

Elenco dei parametri

stream_filter

The stream filter to be removed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 Dynamicly refiltering a stream

<?php
/* Open a test file for reading and writing */
$fp fopen("test.txt""rw");

$rot13_filter stream_filter_append($fp"string.rot13"STREAM_FILTER_WRITE);
fwrite($fp"This is ");
stream_filter_remove($rot13_filter);
fwrite($fp"a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

?>

Il precedente esempio visualizzerà:

Guvf vf a test

Vedere anche:



stream_get_contents

(PHP 5)

stream_get_contentsReads remainder of a stream into a string

Descrizione

string stream_get_contents ( resource $handle [, int $maxlength = -1 [, int $offset = -1 ]] )

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Elenco dei parametri

handle (resource)

A stream resource (e.g. returned from fopen())

maxlength (integer)

The maximum bytes to read. Defaults to -1 (read all the remaining buffer).

offset (integer)

Seek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position.

Valori restituiti

Returns a string o FALSE in caso di fallimento.

Log delle modifiche

Versione Descrizione
5.1.0 The offset was added.

Esempi

Example #1 stream_get_contents() example

<?php

if ($stream fopen('http://www.example.com''r')) {
    
// print all the page starting at the offset 10
    
echo stream_get_contents($stream, -110);

    
fclose($stream);
}


if (
$stream fopen('http://www.example.net''r')) {
    
// print the first 5 bytes
    
echo stream_get_contents($stream5);

    
fclose($stream);
}

?>

Note

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche:

  • fgets() - Prende una riga da un puntatore a file
  • fread() - Legge un file salvaguardando la corrispondenza binaria
  • fpassthru() - Invia tutti i dati rimanenti su un puntartore a file



stream_get_filters

(PHP 5)

stream_get_filtersRetrieve list of registered filters

Descrizione

array stream_get_filters ( void )

Retrieve the list of registered filters on the running system.

Valori restituiti

Returns an indexed array containing the name of all stream filters available.

Esempi

Example #1 Using stream_get_filters()

<?php
$streamlist 
stream_get_filters();
print_r($streamlist);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

Vedere anche:



stream_get_line

(PHP 5)

stream_get_lineGets line from stream resource up to a given delimiter

Descrizione

string stream_get_line ( resource $handle , int $length [, string $ending ] )

Gets a line from the given handle.

Reading ends when length bytes have been read, when the string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

Elenco dei parametri

handle

A valid file handle.

length

The number of bytes to read from the handle.

ending

An optional string delimiter.

Valori restituiti

Returns a string of up to length bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

Vedere anche:

  • fread() - Legge un file salvaguardando la corrispondenza binaria
  • fgets() - Prende una riga da un puntatore a file
  • fgetc() - Prende un carattere da un puntatore a file


stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5)

stream_get_meta_dataRetrieves header/meta data from streams/file pointers

Descrizione

array stream_get_meta_data ( resource $stream )

Returns information about an existing stream.

Elenco dei parametri

stream

The stream can be any stream created by fopen(), fsockopen() and pfsockopen().

Valori restituiti

The result array contains the following items:

  • timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().

  • blocked (bool) - TRUE if the stream is in blocking IO mode. See stream_set_blocking().

  • eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

  • unread_bytes (int) - the number of bytes currently contained in the PHP's own internal buffer.

    Nota: You shouldn't use this value in a script.

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Supported Protocols and Wrappers for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Supported Protocols and Wrappers for more information about wrappers and their wrapper data.

  • mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)

  • seekable (bool) - whether the current stream can be seeked.

  • uri (string) - the URI/filename associated with this stream.

Log delle modifiche

Versione Descrizione
5.0.0 The following entries were added in the returned array: mode, seekable, and uri.
4.3.0 The following entries were added in the returned array: stream_type, wrapper_type, wrapper_data, and filters.
4.3.0 socket_get_status() is an alias for this function. Prior to PHP 4.3.0, it was used to retrieve the first four items, for socket based streams only.

Esempi

Example #1 stream_get_meta_data() example

<?php
$url 
'http://www.example.com/';

if (!
$fp fopen($url'r')) {
    
trigger_error("Unable to open URL ($url)"E_USER_ERROR);
}

$meta stream_get_meta_data($fp);

print_r($meta);

fclose($fp);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [wrapper_data] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Server: Apache/2.2.3 (Red Hat)
            [2] => Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
            [3] => ETag: "b300b4-1b6-4059a80bfd280"
            [4] => Accept-Ranges: bytes
            [5] => Content-Type: text/html; charset=UTF-8
            [6] => Set-Cookie: FOO=BAR; expires=Fri, 21-Dec-2012 12:00:00 GMT; path=/; domain=.example.com
            [6] => Connection: close     
            [7] => Date: Fri, 16 Oct 2009 12:00:00 GMT
            [8] => Age: 1164   
            [9] => Content-Length: 438
        )

    [wrapper_type] => http
    [stream_type] => tcp_socket/ssl
    [mode] => r
    [unread_bytes] => 438
    [seekable] => 
    [uri] => http://www.example.com/
    [timed_out] => 
    [blocked] => 1
    [eof] => 
)

Note

Nota:

This function does NOT work on sockets created by the Socket extension.

Vedere anche:



stream_get_transports

(PHP 5)

stream_get_transportsRetrieve list of registered socket transports

Descrizione

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Valori restituiti

Returns an indexed array of socket transports names.

Esempi

Example #1 Using stream_get_transports()

<?php
$xportlist 
stream_get_transports();
print_r($xportlist);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

Vedere anche:



stream_get_wrappers

(PHP 5)

stream_get_wrappersRetrieve list of registered streams

Descrizione

array stream_get_wrappers ( void )

Retrieve list of registered streams available on the running system.

Valori restituiti

Returns an indexed array containing the name of all stream wrappers available on the running system.

Esempi

Example #1 stream_get_wrappers() example

<?php
print_r
(stream_get_wrappers());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Example #2 Checking for the existence of a stream wrapper

<?php
// check for the existence of the bzip2 stream wrapper
if (in_array('compress.bzip2'stream_get_wrappers())) {
    echo 
'compress.bzip2:// support enabled.';
} else {
    echo 
'compress.bzip2:// support not enabled.';
}
?>

Vedere anche:



stream_is_local

(PHP 5 >= 5.2.4)

stream_is_localChecks if a stream is a local stream

Descrizione

bool stream_is_local ( mixed $stream_or_url )

Checks if a stream, or a URL, is a local one or not.

Elenco dei parametri

stream_or_url

The stream resource or URL to check.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 stream_is_local() example

Basic usage example.

<?php
var_dump
(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(false)
bool(true)



stream_notification_callback

(PHP 5 >= 5.2.0)

stream_notification_callbackA callback function for the notification context paramater

Descrizione

void stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max )

A callable function, used by the notification context parameter, called during an event.

Nota:

This is not a real function, only a prototype of how the function should be.

Elenco dei parametri

notification_code

One of the STREAM_NOTIFY_* notification constants.

severity

One of the STREAM_NOTIFY_SEVERITY_* notification constants.

message

Passed if a descriptive message is available for the event.

message_code

Passed if a descriptive message code is available for the event.

The meaning of this value is dependent on the specific wrapper in use.

bytes_transferred

If applicable, the bytes_transferred will be populated.

bytes_max

If applicable, the bytes_max will be populated.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 stream_notification_callback() example

<?php
function stream_notification_callback($notification_code$severity$message$message_code$bytes_transferred$bytes_max) {

    switch(
$notification_code) {
        case 
STREAM_NOTIFY_RESOLVE:
        case 
STREAM_NOTIFY_AUTH_REQUIRED:
        case 
STREAM_NOTIFY_COMPLETED:
        case 
STREAM_NOTIFY_FAILURE:
        case 
STREAM_NOTIFY_AUTH_RESULT:
            
var_dump($notification_code$severity$message$message_code$bytes_transferred$bytes_max);
            
/* Ignore */
            
break;

        case 
STREAM_NOTIFY_REDIRECTED:
            echo 
"Being redirected to: "$message;
            break;

        case 
STREAM_NOTIFY_CONNECT:
            echo 
"Connected...";
            break;

        case 
STREAM_NOTIFY_FILE_SIZE_IS:
            echo 
"Got the filesize: "$bytes_max;
            break;

        case 
STREAM_NOTIFY_MIME_TYPE_IS:
            echo 
"Found the mime-type: "$message;
            break;

        case 
STREAM_NOTIFY_PROGRESS:
            echo 
"Made some progress, downloaded "$bytes_transferred" so far";
            break;
    }
    echo 
"\n";
}

$ctx stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

file_get_contents("http://php.net/contact"false$ctx);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Connected...
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;charset=utf-8
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 1440 so far
Made some progress, downloaded 2880 so far
Made some progress, downloaded 4320 so far
Made some progress, downloaded 5760 so far
Made some progress, downloaded 6381 so far
Made some progress, downloaded 7002 so far

Example #2 Simple progressbar for commandline download client

<?php
function usage($argv) {
    echo 
"Usage:\n";
    
printf("\tphp %s <http://example.com/file> <localfile>\n"$argv[0]);
    exit(
1);
}

function 
stream_notification_callback($notification_code$severity$message$message_code$bytes_transferred$bytes_max) {
    static 
$filesize null;

    switch(
$notification_code) {
    case 
STREAM_NOTIFY_RESOLVE:
    case 
STREAM_NOTIFY_AUTH_REQUIRED:
    case 
STREAM_NOTIFY_COMPLETED:
    case 
STREAM_NOTIFY_FAILURE:
    case 
STREAM_NOTIFY_AUTH_RESULT:
        
/* Ignore */
        
break;

    case 
STREAM_NOTIFY_REDIRECTED:
        echo 
"Being redirected to: "$message"\n";
        break;

    case 
STREAM_NOTIFY_CONNECT:
        echo 
"Connected...\n";
        break;

    case 
STREAM_NOTIFY_FILE_SIZE_IS:
        
$filesize $bytes_max;
        echo 
"Filesize: "$filesize"\n";
        break;

    case 
STREAM_NOTIFY_MIME_TYPE_IS:
        echo 
"Mime-type: "$message"\n";
        break;

    case 
STREAM_NOTIFY_PROGRESS:
        if (
$bytes_transferred 0) {
            if (!isset(
$filesize)) {
                
printf("\rUnknown filesize.. %2d kb done.."$bytes_transferred/1024);
            } else {
                
$length = (int)(($bytes_transferred/$filesize)*100);
                
printf("\r[%-100s] %d%% (%2d/%2d kb)"str_repeat("="$length). ">"$length, ($bytes_transferred/1024), $filesize/1024);
            }
        }
        break;
    }
}

isset(
$argv[1], $argv[2]) or usage($argv);

$ctx stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

$fp fopen($argv[1], "r"false$ctx);
if (
is_resource($fp) && file_put_contents($argv[2], $fp)) {
    echo 
"\nDone!\n";
    exit(
0);
}

$err error_get_last();
echo 
"\nErrrrrorr..\n"$err["message"], "\n";
exit(
1);
?>

Executing the example above with: php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2 will output something similar too:

Connected...
Mime-type: text/html; charset=utf-8
Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2
Connected...
Filesize: 7773024
Mime-type: application/octet-stream
[========================================>                                                           ] 40% (3076/7590 kb)

Vedere anche:



stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5)

stream_register_wrapperAlias di stream_wrapper_register()

Descrizione

Questa funzione è sinonimo di: stream_wrapper_register().



stream_resolve_include_path

(PHP 5 >= 5.3.2)

stream_resolve_include_path Resolve filename against the include path

Descrizione

string stream_resolve_include_path ( string $filename )

Resolve filename against the include path according to the same rules as fopen()/include.

Elenco dei parametri

filename

The filename to resolve.

Valori restituiti

Returns a string containing the resolved absolute filename, o FALSE in caso di fallimento.

Esempi

Example #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump
(stream_resolve_include_path("test.php"));
?>

Il precedente esempio visualizzerà qualcosa simile a:

string(22) "/var/www/html/test.php"



stream_select

(PHP 4 >= 4.3.0, PHP 5)

stream_selectRuns the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

Descrizione

int stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

Elenco dei parametri

read

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

write

The streams listed in the write array will be watched to see if a write will not block.

except

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Nota:

When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.
tv_sec

The tv_sec and tv_usec together form the timeout parameter, tv_sec specifies the number of seconds while tv_usec the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If tv_sec and tv_usec are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams.

If tv_sec is NULL stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

Avviso

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

tv_usec

See tv_sec description.

Valori restituiti

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

Esempi

Example #1 stream_select() Example

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

<?php
/* Prepare the read array */
$read   = array($stream1$stream2);
$write  NULL;
$except NULL;
if (
false === ($num_changed_streams stream_select($read$write$except0))) {
    
/* Error handling */
} elseif ($num_changed_streams 0) {
    
/* At least on one of the streams something interesting happened */
}
?>

Note

Nota:

Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

<?php
$e 
NULL;
stream_select($r$w$e0);
?>

Nota:

Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:

<?php
$e 
NULL;
if (
false === stream_select($r$w$e0)) {
    echo 
"stream_select() failed\n";
}
?>

Nota:

If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Nota:

Some streams (like zlib) cannot be selected by this function.

Nota:

Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.

Vedere anche:



stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5)

stream_set_blockingSet blocking/non-blocking mode on a stream

Descrizione

bool stream_set_blocking ( resource $stream , int $mode )

Sets blocking or non-blocking mode on a stream.

This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

Elenco dei parametri

stream

The stream.

mode

If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Log delle modifiche

Versione Descrizione
4.3.0 Prior to PHP 4.3.0, this function only worked on socket based streams.

Note

Nota:

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Vedere anche:

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec


stream_set_chunk_size

(PHP 5 >= 5.4.0)

stream_set_chunk_sizeSet the stream chunk size

Descrizione

int stream_set_chunk_size ( resource $fp , int $chunk_size )

Set the stream chunk size.

Elenco dei parametri

fp

The target stream.

chunk_size

The desired new chunk size.

Valori restituiti

Returns the previous chunk size on success.

Will return FALSE if chunk_size is less than 1 or greater than PHP_INT_MAX.

Errori/Eccezioni

Will emit an E_WARNING level error if chunk_size is less than 1 or greater than PHP_INT_MAX.



stream_set_read_buffer

(PHP 5 >= 5.3.3)

stream_set_read_bufferSet read file buffering on the given stream

Descrizione

int stream_set_read_buffer ( resource $stream , int $buffer )

Sets the read buffer. It's the equivalent of stream_set_write_buffer(), but for read operations.

Elenco dei parametri

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to read from that input stream.

Valori restituiti

Returns 0 on success, or EOF if the request cannot be honored.

Vedere anche:



stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5)

stream_set_timeoutSet timeout period on a stream

Descrizione

bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )

Sets the timeout value on stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Elenco dei parametri

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Log delle modifiche

Versione Descrizione
4.3.0 As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.

Esempi

Example #1 stream_set_timeout() example

<?php
$fp 
fsockopen("www.example.com"80);
if (!
$fp) {
    echo 
"Unable to open\n";
} else {

    
fwrite($fp"GET / HTTP/1.0\r\n\r\n");
    
stream_set_timeout($fp2);
    
$res fread($fp2000);

    
$info stream_get_meta_data($fp);
    
fclose($fp);

    if (
$info['timed_out']) {
        echo 
'Connection timed out!';
    } else {
        echo 
$res;
    }

}
?>

Note

Nota:

This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

Vedere anche:

  • fsockopen() - Apre una connessione a un socket appartenente a un dominio Internet o Unix
  • fopen() - Apre un file o un URL


stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5)

stream_set_write_bufferSets write file buffering on the given stream

Descrizione

int stream_set_write_buffer ( resource $stream , int $buffer )

Sets the buffering for write operations on the given stream to buffer bytes.

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write.

Elenco dei parametri

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

Valori restituiti

Returns 0 on success, or EOF if the request cannot be honored.

Esempi

Example #1 stream_set_write_buffer() example

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

<?php
$fp 
fopen($file"w");
if (
$fp) {
  
stream_set_write_buffer($fp0);
  
fwrite($fp$output);
  
fclose($fp);
}
?>

Vedere anche:

  • fopen() - Apre un file o un URL
  • fwrite() - Scrive un file salvaguardando la corrispondenza binaria


stream_socket_accept

(PHP 5)

stream_socket_acceptAccept a connection on a socket created by stream_socket_server()

Descrizione

resource stream_socket_accept ( resource $server_socket [, float $timeout = ini_get("default_socket_timeout") [, string &$peername ]] )

Accept a connection on a socket previously created by stream_socket_server().

Elenco dei parametri

server_socket

The server socket to accept a connection from.

timeout

Override the default socket accept timeout. Time should be given in seconds.

peername

Will be set to the name (address) of the client which connected, if included and available from the selected transport.

Nota:

Can also be determined later using stream_socket_get_name().

Valori restituiti

Returns a stream to the accepted socket connection o FALSE in caso di fallimento.

Note

Avviso

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

Vedere anche:



stream_socket_client

(PHP 5)

stream_socket_clientOpen Internet or Unix domain socket connection

Descrizione

resource stream_socket_client ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, resource $context ]]]]] )

Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Nota:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Elenco dei parametri

remote_socket

Address to the socket to connect to.

errno

Will be set to the system level error number if connection fails.

errstr

Will be set to the system level error message if the connection fails.

timeout

Number of seconds until the connect() system call should timeout.

Nota: This parameter only applies when not making asynchronous connection attempts.

Nota:

To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.

flags

Bitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

context

A valid context resource created with stream_context_create().

Valori restituiti

On success a stream resource is returned which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()), FALSE on failure.

Errori/Eccezioni

On failure the errno and errstr arguments will be populated with the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Esempi

Example #1 stream_socket_client() example

<?php
$fp 
stream_socket_client("tcp://www.example.com:80"$errno$errstr30);
if (!
$fp) {
    echo 
"$errstr ($errno)<br />\n";
} else {
    
fwrite($fp"GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!
feof($fp)) {
        echo 
fgets($fp1024);
    }
    
fclose($fp);
}
?>

Example #2 Using UDP connection

Retrieving the day and time from the UDP service "daytime" (port 13) on localhost.

<?php
$fp 
stream_socket_client("udp://127.0.0.1:13"$errno$errstr);
if (!
$fp) {
    echo 
"ERROR: $errno - $errstr<br />\n";
} else {
    
fwrite($fp"\n");
    echo 
fread($fp26);
    
fclose($fp);
}
?>

Note

Avviso

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Nota: Nella specifica numerica degli indirizzi IPv6 (es. fe80::1) occorre racchiudere l'IP tra parentesi quadre. Ad esempio, tcp://[fe80::1]:80.

Nota:

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of built in transports.

Vedere anche:

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • fgets() - Prende una riga da un puntatore a file
  • fgetss() - Prende una riga da un puntatore a file ed elimina i tag HTML
  • fwrite() - Scrive un file salvaguardando la corrispondenza binaria
  • fclose() - Chiude un puntatore a file aperto
  • feof() - Verifica se è stata raggiunta la fine del file su un puntatore a file
  • cURL Funzioni



stream_socket_enable_crypto

(PHP 5 >= 5.1.0)

stream_socket_enable_cryptoTurns encryption on/off on an already connected socket

Descrizione

mixed stream_socket_enable_crypto ( resource $stream , bool $enable [, int $crypto_type [, resource $session_stream ]] )

Enable or disable encryption on the stream.

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

Elenco dei parametri

stream

The stream resource.

enable

Enable/disable cryptography on the stream.

crypto_type

Setup encryption on the stream. Valid methods are

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER

session_stream

Seed the stream with settings from session_stream.

Valori restituiti

Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

Esempi

Example #1 stream_socket_enable_crypto() example

<?php
$fp 
stream_socket_client("tcp://myproto.example.com:31337"$errno$errstr30);
if (!
$fp) {
    die(
"Unable to connect: $errstr ($errno)");
}

/* Turn on encryption for login phase */
stream_socket_enable_crypto($fptrueSTREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp"USER god\r\n");
fwrite($fp"PASS secret\r\n");

/* Turn off encryption for the rest */
stream_socket_enable_crypto($fpfalse);

while (
$motd fgets($fp)) {
    echo 
$motd;
}

fclose($fp);
?>

Il precedente esempio visualizzerà qualcosa simile a:



stream_socket_get_name

(PHP 5)

stream_socket_get_nameRetrieve the name of the local or remote sockets

Descrizione

string stream_socket_get_name ( resource $handle , bool $want_peer )

Returns the local or remote name of a given socket connection.

Elenco dei parametri

handle

The socket to get the name of.

want_peer

If set to TRUE the remote socket name will be returned, if set to FALSE the local socket name will be returned.

Valori restituiti

The name of the socket.

Vedere anche:



stream_socket_pair

(PHP 5 >= 5.1.0)

stream_socket_pair Creates a pair of connected, indistinguishable socket streams

Descrizione

array stream_socket_pair ( int $domain , int $type , int $protocol )

stream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).

Elenco dei parametri

domain

The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM

protocol

The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP

Nota: Please consult the Streams constant list for further details on each constant.

Valori restituiti

Returns an array with the two socket resources on success, or FALSE on failure.

Log delle modifiche

Versione Descrizione
5.3.0 This function is now available on Windows platforms.

Esempi

Example #1 A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.

<?php

$sockets 
stream_socket_pair(STREAM_PF_UNIXSTREAM_SOCK_STREAMSTREAM_IPPROTO_IP);
$pid     pcntl_fork();

if (
$pid == -1) {
     die(
'could not fork');

} else if (
$pid) {
     
/* parent */
    
fclose($sockets[0]);

    
fwrite($sockets[1], "child PID: $pid\n");
    echo 
fgets($sockets[1]);

    
fclose($sockets[1]);

} else {
    
/* child */
    
fclose($sockets[1]);

    
fwrite($sockets[0], "message from child\n");
    echo 
fgets($sockets[0]);

    
fclose($sockets[0]);
}

?>

Il precedente esempio visualizzerà qualcosa simile a:

child PID: 1378
message from child



stream_socket_recvfrom

(PHP 5)

stream_socket_recvfromReceives data from a socket, connected or not

Descrizione

string stream_socket_recvfrom ( resource $socket , int $length [, int $flags = 0 [, string &$address ]] )

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

Elenco dei parametri

socket

The remote socket.

length

The number of bytes to receive from the socket.

flags

The value of flags can be any combination of the following:

Possible values for flags
STREAM_OOB Process OOB (out-of-band) data.
STREAM_PEEK Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

address

If address is provided it will be populated with the address of the remote socket.

Valori restituiti

Returns the read data, as a string

Esempi

Example #1 stream_socket_recvfrom() example

<?php
/* Open a server socket to port 1234 on localhost */
$server stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" stream_socket_recvfrom($socket1500STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't comsume it. */
echo "Data: '" stream_socket_recvfrom($socket1500STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" stream_socket_recvfrom($socket1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?>

Note

Nota:

If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

Nota:

Calls to stream_socket_recvfrom() on socket-based streams, after calls to buffer-based stream functions (like fread() or stream_get_line()) read data directly from the socket and bypass the stream buffer.

Vedere anche:



stream_socket_sendto

(PHP 5)

stream_socket_sendtoSends a message to a socket, whether it is connected or not

Descrizione

int stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string $address ]] )

Sends the specified data through the socket.

Elenco dei parametri

socket

The socket to send data to.

data

The data to be sent.

flags

The value of flags can be any combination of the following:

possible values for flags
STREAM_OOB Process OOB (out-of-band) data.

address

The address specified when the socket stream was created will be used unless an alternate address is specified in address.

If specified, it must be in dotted quad (or [ipv6]) format.

Valori restituiti

Returns a result code, as an integer.

Esempi

Example #1 stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket"Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket"Out of Band data."STREAM_OOB);

/* Close it up */
fclose($socket);
?>

Vedere anche:



stream_socket_server

(PHP 5)

stream_socket_serverCreate an Internet or Unix domain server socket

Descrizione

resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )

Creates a stream or datagram socket on the specified local_socket.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

Elenco dei parametri

local_socket

The type of socket created is determined by the transport specified using standard URL formatting: transport://target.

For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of bulitin transports.

errno

If the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

errstr

See errno description.

flags

A bitmask field which may be set to any combination of socket creation flags.

Nota:

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

context

Valori restituiti

Returns the created stream, or FALSE on error.

Esempi

Example #1 Using TCP server sockets

<?php
$socket 
stream_socket_server("tcp://0.0.0.0:8000"$errno$errstr);
if (!
$socket) {
  echo 
"$errstr ($errno)<br />\n";
} else {
  while (
$conn stream_socket_accept($socket)) {
    
fwrite($conn'The local time is ' date('n/j/Y g:i a') . "\n");
    
fclose($conn);
  }
  
fclose($socket);
}
?>

The example below shows how to act as a time server which can respond to time queries as shown in an example on stream_socket_client().

Nota: Most systems require root access to create a server socket on a port below 1024.

Example #2 Using UDP server sockets

<?php
$socket 
stream_socket_server("udp://127.0.0.1:1113"$errno$errstrSTREAM_SERVER_BIND);
if (!
$socket) {
    die(
"$errstr ($errno)");
}

do {
    
$pkt stream_socket_recvfrom($socket10$peer);
    echo 
"$peer\n";
    
stream_socket_sendto($socketdate("D M j H:i:s Y\r\n"), 0$peer);
} while (
$pkt !== false);

?>

Note

Nota: Nella specifica numerica degli indirizzi IPv6 (es. fe80::1) occorre racchiudere l'IP tra parentesi quadre. Ad esempio, tcp://[fe80::1]:80.

Vedere anche:



stream_socket_shutdown

(PHP 5 >= 5.2.1)

stream_socket_shutdownShutdown a full-duplex connection

Descrizione

bool stream_socket_shutdown ( resource $stream , int $how )

Shutdowns (partially or not) a full-duplex connection.

Elenco dei parametri

stream

An open stream (opened with stream_socket_client(), for example)

how

One of the following constants: STREAM_SHUT_RD (disable further receptions), STREAM_SHUT_WR (disable further transmissions) or STREAM_SHUT_RDWR (disable further receptions and transmissions).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 A stream_socket_shutdown() example

<?php

$server 
stream_socket_server('tcp://127.0.0.1:1337');
$client stream_socket_client('tcp://127.0.0.1:1337');

var_dump(fputs($client"hello"));

stream_socket_shutdown($clientSTREAM_SHUT_WR);
var_dump(fputs($client"hello")); // doesn't work now

?>

Il precedente esempio visualizzerà qualcosa simile a:

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

Vedere anche:

  • fclose() - Chiude un puntatore a file aperto



stream_supports_lock

(PHP 5 >= 5.3.0)

stream_supports_lockTells whether the stream supports locking.

Descrizione

bool stream_supports_lock ( resource $stream )

Tells whether the stream supports locking through flock().

Elenco dei parametri

stream

The stream to check.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

  • flock() - Sistema di bloccaggio file



stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5)

stream_wrapper_registerRegister a URL wrapper implemented as a PHP class

Descrizione

bool stream_wrapper_register ( string $protocol , string $classname [, int $flags = 0 ] )

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Elenco dei parametri

protocol

The wrapper name to be registered.

classname

The classname which implements the protocol.

flags

Should be set to STREAM_IS_URL if protocol is a URL protocol. Default is 0, local stream.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

Log delle modifiche

Versione Descrizione
5.2.4 Added the flags parameter.

Esempi

Example #1 How to register a stream wrapper

<?php
$existed 
in_array("var"stream_get_wrappers());
if (
$existed) {
    
stream_wrapper_unregister("var");
}
stream_wrapper_register("var""VariableStream");
$myvar "";

$fp fopen("var://myvar""r+");

fwrite($fp"line1\n");
fwrite($fp"line2\n");
fwrite($fp"line3\n");

rewind($fp);
while (!
feof($fp)) {
    echo 
fgets($fp);
}
fclose($fp);
var_dump($myvar);

if (
$existed) {
    
stream_wrapper_restore("var");
}

?>

Il precedente esempio visualizzerà:

line1
line2
line3
string(18) "line1
line2
line3
"

Vedere anche:



stream_wrapper_restore

(PHP 5 >= 5.1.0)

stream_wrapper_restoreRestores a previously unregistered built-in wrapper

Descrizione

bool stream_wrapper_restore ( string $protocol )

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

Elenco dei parametri

protocol

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.



stream_wrapper_unregister

(PHP 5 >= 5.1.0)

stream_wrapper_unregisterUnregister a URL wrapper

Descrizione

bool stream_wrapper_unregister ( string $protocol )

Allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

Elenco dei parametri

protocol

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.


Indice dei contenuti




Tidy


Introduzione

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.



Installazione/Configurazione

Indice dei contenuti


Requisiti

To use Tidy, you will need libtidy installed, available on the tidy homepage » http://tidy.sourceforge.net/.



Installazione

This extension is bundled with PHP 5 and greater, and is installed using the --with-tidy configure option.

PHP 4 users may use the (old) PECL extension here: » http://pecl.php.net/package/tidy.

Nota:

Tidy 1.0 is for PHP 4, whereas newer versions of the Tidy extension are for PHP 5 and greater.



Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tidy Configuration Options
Nome Default Modificabile Storico dei cambiamenti
tidy.default_config "" PHP_INI_SYSTEM  
tidy.clean_output "0" PHP_INI_USER PHP_INI_PERDIR prior to PHP 5.4.0
Per maggiori dettagli e definizioni sui modi PHP_INI_*, vedere Where a configuration setting may be set.

Breve descrizione dei parametri di configurazione.

tidy.default_config string

Default path for tidy config file.

tidy.clean_output boolean

Turns on/off the output repairing by Tidy.

Avviso

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.



Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.




Costanti predefinite

Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a "<a href="XX">link</a>" tag. Each TIDY_ATTR_XXX represents a HTML attribute. For example TIDY_ATTR_HREF would represent the href attribute in the previous example.

The following constants are defined:

tidy tag constants
constant
TIDY_TAG_UNKNOWN
TIDY_TAG_A
TIDY_TAG_ABBR
TIDY_TAG_ACRONYM
TIDY_TAG_ALIGN
TIDY_TAG_APPLET
TIDY_TAG_AREA
TIDY_TAG_B
TIDY_TAG_BASE
TIDY_TAG_BASEFONT
TIDY_TAG_BDO
TIDY_TAG_BGSOUND
TIDY_TAG_BIG
TIDY_TAG_BLOCKQUOTE
TIDY_TAG_BODY
TIDY_TAG_BR
TIDY_TAG_BUTTON
TIDY_TAG_CAPTION
TIDY_TAG_CENTER
TIDY_TAG_CITE
TIDY_TAG_CODE
TIDY_TAG_COL
TIDY_TAG_COLGROUP
TIDY_TAG_COMMENT
TIDY_TAG_DD
TIDY_TAG_DEL
TIDY_TAG_DFN
TIDY_TAG_DIR
TIDY_TAG_DIV
TIDY_TAG_DL
TIDY_TAG_DT
TIDY_TAG_EM
TIDY_TAG_EMBED
TIDY_TAG_FIELDSET
TIDY_TAG_FONT
TIDY_TAG_FORM
TIDY_TAG_FRAME
TIDY_TAG_FRAMESET
TIDY_TAG_H1
TIDY_TAG_H2
TIDY_TAG_H3
TIDY_TAG_H4
TIDY_TAG_H5
TIDY_TAG_H6
TIDY_TAG_HEAD
TIDY_TAG_HR
TIDY_TAG_HTML
TIDY_TAG_I
TIDY_TAG_IFRAME
TIDY_TAG_ILAYER
TIDY_TAG_IMG
TIDY_TAG_INPUT
TIDY_TAG_INS
TIDY_TAG_ISINDEX
TIDY_TAG_KBD
TIDY_TAG_KEYGEN
TIDY_TAG_LABEL
TIDY_TAG_LAYER
TIDY_TAG_LEGEND
TIDY_TAG_LI
TIDY_TAG_LISTING
TIDY_TAG_MAP
TIDY_TAG_MARQUEE
TIDY_TAG_MENU
TIDY_TAG_META
TIDY_TAG_MULTICOL
TIDY_TAG_NOBR
TIDY_TAG_NOEMBED
TIDY_TAG_NOFRAMES
TIDY_TAG_NOLAYER
TIDY_TAG_NOSAVE
TIDY_TAG_NOSCRIPT
TIDY_TAG_OBJECT
TIDY_TAG_OL
TIDY_TAG_OPTGROUP
TIDY_TAG_OPTION
TIDY_TAG_P
TIDY_TAG_PARAM
TIDY_TAG_PLAINTEXT
TIDY_TAG_PRE
TIDY_TAG_Q
TIDY_TAG_RP
TIDY_TAG_RT
TIDY_TAG_RTC
TIDY_TAG_RUBY
TIDY_TAG_S
TIDY_TAG_SAMP
TIDY_TAG_SCRIPT
TIDY_TAG_SELECT
TIDY_TAG_SERVER
TIDY_TAG_SERVLET
TIDY_TAG_SMALL
TIDY_TAG_SPACER
TIDY_TAG_SPAN
TIDY_TAG_STRIKE
TIDY_TAG_STRONG
TIDY_TAG_STYLE
TIDY_TAG_SUB
TIDY_TAG_TABLE
TIDY_TAG_TBODY
TIDY_TAG_TD
TIDY_TAG_TEXTAREA
TIDY_TAG_TFOOT
TIDY_TAG_TH
TIDY_TAG_THEAD
TIDY_TAG_TITLE
TIDY_TAG_TR
TIDY_TAG_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

tidy attribute constants
constant
TIDY_ATTR_UNKNOWN
TIDY_ATTR_ABBR
TIDY_ATTR_ACCEPT
TIDY_ATTR_ACCEPT_CHARSET
TIDY_ATTR_ACCESSKEY
TIDY_ATTR_ACTION
TIDY_ATTR_ADD_DATE
TIDY_ATTR_ALIGN
TIDY_ATTR_ALT
TIDY_ATTR_ARCHIVE
TIDY_ATTR_AXIS
TIDY_ATTR_BACKGROUND
TIDY_ATTR_BGCOLOR
TIDY_ATTR_BGPROPERTIES
TIDY_ATTR_BORDER
TIDY_ATTR_BORDERCOLOR
TIDY_ATTR_BOTTOMMARGIN
TIDY_ATTR_CELLPADDING
TIDY_ATTR_CELLSPACING
TIDY_ATTR_CHAR
TIDY_ATTR_CHAROFF
TIDY_ATTR_CHARSET
TIDY_ATTR_CHECKED
TIDY_ATTR_CITE
TIDY_ATTR_CLASS
TIDY_ATTR_CLASSID
TIDY_ATTR_CLEAR
TIDY_ATTR_CODE
TIDY_ATTR_CODEBASE
TIDY_ATTR_CODETYPE
TIDY_ATTR_COLOR
TIDY_ATTR_COLS
TIDY_ATTR_COLSPAN
TIDY_ATTR_COMPACT
TIDY_ATTR_CONTENT
TIDY_ATTR_COORDS
TIDY_ATTR_DATA
TIDY_ATTR_DATAFLD
TIDY_ATTR_DATAPAGESIZE
TIDY_ATTR_DATASRC
TIDY_ATTR_DATETIME
TIDY_ATTR_DECLARE
TIDY_ATTR_DEFER
TIDY_ATTR_DIR
TIDY_ATTR_DISABLED
TIDY_ATTR_ENCODING
TIDY_ATTR_ENCTYPE
TIDY_ATTR_FACE
TIDY_ATTR_FOR
TIDY_ATTR_FRAME
TIDY_ATTR_FRAMEBORDER
TIDY_ATTR_FRAMESPACING
TIDY_ATTR_GRIDX
TIDY_ATTR_GRIDY
TIDY_ATTR_HEADERS
TIDY_ATTR_HEIGHT
TIDY_ATTR_HREF
TIDY_ATTR_HREFLANG
TIDY_ATTR_HSPACE
TIDY_ATTR_HTTP_EQUIV
TIDY_ATTR_ID
TIDY_ATTR_ISMAP
TIDY_ATTR_LABEL
TIDY_ATTR_LANG
TIDY_ATTR_LANGUAGE
TIDY_ATTR_LAST_MODIFIED
TIDY_ATTR_LAST_VISIT
TIDY_ATTR_LEFTMARGIN
TIDY_ATTR_LONGDESC
TIDY_ATTR_LOWSRC
TIDY_ATTR_MARGINHEIGHT
TIDY_ATTR_MARGINWIDTH
TIDY_ATTR_MAXLENGTH
TIDY_ATTR_MEDIA
TIDY_ATTR_METHOD
TIDY_ATTR_MULTIPLE
TIDY_ATTR_NAME
TIDY_ATTR_NOHREF
TIDY_ATTR_NORESIZE
TIDY_ATTR_NOSHADE
TIDY_ATTR_NOWRAP
TIDY_ATTR_OBJECT
TIDY_ATTR_OnAFTERUPDATE
TIDY_ATTR_OnBEFOREUNLOAD
TIDY_ATTR_OnBEFOREUPDATE
TIDY_ATTR_OnBLUR
TIDY_ATTR_OnCHANGE
TIDY_ATTR_OnCLICK
TIDY_ATTR_OnDATAAVAILABLE
TIDY_ATTR_OnDATASETCHANGED
TIDY_ATTR_OnDATASETCOMPLETE
TIDY_ATTR_OnDBLCLICK
TIDY_ATTR_OnERRORUPDATE
TIDY_ATTR_OnFOCUS
TIDY_ATTR_OnKEYDOWN
TIDY_ATTR_OnKEYPRESS
TIDY_ATTR_OnKEYUP
TIDY_ATTR_OnLOAD
TIDY_ATTR_OnMOUSEDOWN
TIDY_ATTR_OnMOUSEMOVE
TIDY_ATTR_OnMOUSEOUT
TIDY_ATTR_OnMOUSEOVER
TIDY_ATTR_OnMOUSEUP
TIDY_ATTR_OnRESET
TIDY_ATTR_OnROWENTER
TIDY_ATTR_OnROWEXIT
TIDY_ATTR_OnSELECT
TIDY_ATTR_OnSUBMIT
TIDY_ATTR_OnUNLOAD
TIDY_ATTR_PROFILE
TIDY_ATTR_PROMPT
TIDY_ATTR_RBSPAN
TIDY_ATTR_READONLY
TIDY_ATTR_REL
TIDY_ATTR_REV
TIDY_ATTR_RIGHTMARGIN
TIDY_ATTR_ROWS
TIDY_ATTR_ROWSPAN
TIDY_ATTR_RULES
TIDY_ATTR_SCHEME
TIDY_ATTR_SCOPE
TIDY_ATTR_SCROLLING
TIDY_ATTR_SELECTED
TIDY_ATTR_SHAPE
TIDY_ATTR_SHOWGRID
TIDY_ATTR_SHOWGRIDX
TIDY_ATTR_SHOWGRIDY
TIDY_ATTR_SIZE
TIDY_ATTR_SPAN
TIDY_ATTR_SRC
TIDY_ATTR_STANDBY
TIDY_ATTR_START
TIDY_ATTR_STYLE
TIDY_ATTR_SUMMARY
TIDY_ATTR_TABINDEX
TIDY_ATTR_TARGET
TIDY_ATTR_TEXT
TIDY_ATTR_TITLE
TIDY_ATTR_TOPMARGIN
TIDY_ATTR_TYPE
TIDY_ATTR_USEMAP
TIDY_ATTR_VALIGN
TIDY_ATTR_VALUE
TIDY_ATTR_VALUETYPE
TIDY_ATTR_VERSION
TIDY_ATTR_VSPACE
TIDY_ATTR_WIDTH
TIDY_ATTR_WRAP
TIDY_ATTR_XML_LANG
TIDY_ATTR_XML_SPACE
TIDY_ATTR_XMLNS

tidy nodetype constants
constant description
TIDY_NODETYPE_ROOT root node
TIDY_NODETYPE_DOCTYPE doctype
TIDY_NODETYPE_COMMENT HTML comment
TIDY_NODETYPE_PROCINS Processing Instruction
TIDY_NODETYPE_TEXT Text
TIDY_NODETYPE_START start tag
TIDY_NODETYPE_END end tag
TIDY_NODETYPE_STARTEND empty tag
TIDY_NODETYPE_CDATA CDATA
TIDY_NODETYPE_SECTION XML section
TIDY_NODETYPE_ASP ASP code
TIDY_NODETYPE_JSTE JSTE code
TIDY_NODETYPE_PHP PHP code
TIDY_NODETYPE_XMLDECL XML declaration



Esempi

Indice dei contenuti


Tidy example

This simple example shows basic Tidy usage.

Example #1 Basic Tidy usage

<?php
ob_start
();
?>
<html>a html document</html>
<?php
$html 
ob_get_clean();

// Specify configuration
$config = array(
           
'indent'         => true,
           
'output-xhtml'   => true,
           
'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html$config'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>




The tidy class

(PHP 5, PECL tidy >= 0.5.2)

Introduzione

An HTML node in an HTML file, as detected by tidy.

Sommario dellla classe

tidy {
/* Proprietà */
string $errorBuffer;
/* Metodi */
tidyNode body ( void )
bool cleanRepair ( void )
__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )
bool diagnose ( void )
array getConfig ( void )
int getHtmlVer ( void )
mixed getOpt ( string $option )
string getOptDoc ( string $optname )
string getRelease ( void )
int getStatus ( void )
tidyNode head ( void )
tidyNode html ( void )
bool isXhtml ( void )
bool isXml ( void )
bool parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
bool parseString ( string $input [, mixed $config [, string $encoding ]] )
string repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
string repairString ( string $data [, mixed $config [, string $encoding ]] )
tidyNode root ( void )
}

tidy::body

tidy_get_body

(PHP 5, PECL tidy 0.5.2-1.0)

tidy::body -- tidy_get_bodyReturns a tidyNode object starting from the <body> tag of the tidy parse tree

Descrizione

Stile orientato agli oggetti

tidyNode tidy::body ( void )

Stile procedurale

tidyNode tidy_get_body ( tidy $object )

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Esempi

Example #1 tidy::getBody() example

<?php
$html 
'
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>'
;

$tidy tidy_parse_string($html);

$body $tidy->Body();
echo 
$body->value;
?>

Il precedente esempio visualizzerà:

<body>
<p>paragraph</p>
</body>

Note

Nota: Questa funzione è disponibile solo con Zend Engine 2 (PHP >= 5.0.0).

Vedere anche:

  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree


tidy::cleanRepair

tidy_clean_repair

(PHP 5, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repairExecute configured cleanup and repair operations on parsed markup

Descrizione

Stile orientato agli oggetti

bool tidy::cleanRepair ( void )

Stile procedurale

bool tidy_clean_repair ( tidy $object )

This function cleans and repairs the given tidy object.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 tidy::cleanrepair() example

<?php
$html 
'<p>test</I>';

$tidy tidy_parse_string($html);
$tidy->cleanRepair();

echo 
$tidy;
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

Vedere anche:



tidy::__construct

(PHP 5, PECL tidy >= 0.5.2)

tidy::__constructConstructs a new tidy object

Descrizione

tidy::__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )

Constructs a new tidy object.

Elenco dei parametri

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Valori restituiti

Returns the new tidy instance.

Esempi

Example #1 tidy::__construct() example

<?php

$html 
= <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy();
$tidy->ParseString($html);

$tidy->cleanRepair();

if (
$tidy->errorBuffer) {
    echo 
"The following errors were detected:\n";
    echo 
$tidy->errorBuffer;
}

?>

Il precedente esempio visualizzerà:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

Vedere anche:



tidy::diagnose

tidy_diagnose

(PHP 5, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnoseRun configured diagnostics on parsed and repaired markup

Descrizione

Stile orientato agli oggetti

bool tidy::diagnose ( void )

Stile procedurale

bool tidy_diagnose ( tidy $object )

Runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 tidy::diagnose() example

<?php

$html 
= <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy tidy_parse_string($html);
$tidy->cleanRepair();

// note the difference between the two outputs
echo $tidy->errorBuffer "\n";

$tidy->diagnose();
echo 
$tidy->errorBuffer;

?>

Il precedente esempio visualizzerà:

line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

Vedere anche:

  • tidy::errorBuffer()


tidy::$errorBuffer

tidy_get_error_buffer

(PHP 5, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_bufferReturn warnings and errors which occurred parsing the specified document

Descrizione

Stile orientato agli oggetti (property):

Stile procedurale:

string tidy_get_error_buffer ( tidy $tidy )

Returns warnings and errors which occurred parsing the specified document.

Elenco dei parametri

tidy

L'oggetto Tidy

Valori restituiti

Returns the error buffer as a string.

Esempi

Example #1 tidy_get_error_buffer() example

<?php
$html 
'<p>paragraph</p>';

$tidy tidy_parse_string($html);

echo 
tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

Il precedente esempio visualizzerà:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

Vedere anche:

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document


tidy::getConfig

tidy_get_config

(PHP 5, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_configGet current Tidy configuration

Descrizione

Stile orientato agli oggetti

array tidy::getConfig ( void )

Stile procedurale

array tidy_get_config ( tidy $object )

Gets the list of the configuration options in use by the given tidy object.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns an array of configuration options.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

Esempi

Example #1 tidy::getConfig() example

<?php
$html 
'<p>test</p>';
$config = array('indent' => TRUE,
                
'output-xhtml' => TRUE,
                
'wrap' => 200);

$tidy tidy_parse_string($html$config);

print_r($tidy->getConfig());
?>

Il precedente esempio visualizzerà:

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] =>
    [repeated-attributes] => 1
    [alt-text] =>
    [slide-style] =>
    [error-file] =>
    [output-file] =>
    [write-back] =>
    [markup] => 1
    [show-warnings] => 1
    [quiet] =>
    [indent] => 1
    [hide-endtags] =>
    [input-xml] =>
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] =>
    [add-xml-decl] =>
    [uppercase-tags] =>
    [uppercase-attributes] =>
    [bare] =>
    [clean] =>
    [logical-emphasis] =>
    [drop-proprietary-attributes] =>
    [drop-font-tags] =>
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] =>
    [split] =>
    [numeric-entities] =>
    [quote-marks] =>
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] =>
    [wrap-script-literals] =>
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] =>
    [assume-xml-procins] =>
    [add-xml-space] =>
    [enclose-text] =>
    [enclose-block-text] =>
    [keep-time] =>
    [word-2000] =>
    [tidy-mark] =>
    [gnu-emacs] =>
    [gnu-emacs-file] =>
    [literal-attributes] =>
    [show-body-only] =>
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] =>
    [indent-cdata] =>
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] =>
    [join-styles] => 1
    [escape-cdata] =>
    [language] =>
    [ncr] => 1
    [output-bom] => 2
    [replace-color] =>
    [css-prefix] =>
    [new-inline-tags] =>
    [new-blocklevel-tags] =>
    [new-empty-tags] =>
    [new-pre-tags] =>
    [accessibility-check] => 0
    [vertical-space] =>
    [punctuation-wrap] =>
    [merge-divs] => 1
)

Vedere anche:



tidy::getHtmlVer

tidy_get_html_ver

(PHP 5, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_verGet the Detected HTML version for the specified document

Descrizione

Stile orientato agli oggetti

int tidy::getHtmlVer ( void )

Stile procedurale

int tidy_get_html_ver ( tidy $object )

Returns the detected HTML version for the specified tidy object.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns the detected HTML version.

Avviso

This function is not yet implemented in the Tidylib itself, so it always return 0.



tidy::getOpt

tidy_getopt

(PHP 5, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getoptReturns the value of the specified configuration option for the tidy document

Descrizione

Stile orientato agli oggetti

mixed tidy::getOpt ( string $option )

Stile procedurale

mixed tidy_getopt ( tidy $object , string $option )

Returns the value of the specified option for the specified tidy object.

Elenco dei parametri

object

L'oggetto Tidy

option

You will find a list with each configuration option and their types at: » http://tidy.sourceforge.net/docs/quickref.html.

Valori restituiti

Returns the value of the specified option. The return type depends on the type of the specified one.

Esempi

Example #1 tidy_getopt() example

<?php

$html 
='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>'
;

$config = array('accessibility-check' => 3,
                
'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html$config);


var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

Il precedente esempio visualizzerà:

int(3)
bool(true)
string(9) "some text"



tidy::getOptDoc

tidy_get_opt_doc

(PHP 5 >= 5.1.0)

tidy::getOptDoc -- tidy_get_opt_doc Returns the documentation for the given option name

Descrizione

Stile orientato agli oggetti

string tidy::getOptDoc ( string $optname )

Stile procedurale

string tidy_get_opt_doc ( tidy $object , string $optname )

tidy_get_opt_doc() returns the documentation for the given option name.

Nota:

You need at least libtidy from 25 April, 2005 for this function be available.

Elenco dei parametri

object

L'oggetto Tidy

optname

The option name

Valori restituiti

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Esempi

Example #1 Print all options along with their documentation and default value

<?php

$tidy 
= new tidy;
$config $tidy->getConfig();

ksort($config);

foreach (
$config as $opt => $val) {

    if (!
$doc $tidy->getOptDoc($opt))
        
$doc 'no documentation available!';

    
$val = ($tidy->getOpt($opt) === true)  ? 'true'  $val;
    
$val = ($tidy->getOpt($opt) === false) ? 'false' $val;

    echo 
"<p><b>$opt</b> (default: '$val')<br />".
         
"$doc</p><hr />\n";
}

?>

Vedere anche:



tidy::getRelease

tidy_get_release

(PHP 5, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_releaseGet release date (version) for Tidy library

Descrizione

Stile orientato agli oggetti

string tidy::getRelease ( void )

Stile procedurale

string tidy_get_release ( void )

Gets the release date of the Tidy library.

Valori restituiti

Returns a string with the release date of the Tidy library.



tidy::getStatus

tidy_get_status

(PHP 5, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_statusGet status of specified document

Descrizione

Stile orientato agli oggetti

int tidy::getStatus ( void )

Stile procedurale

int tidy_get_status ( tidy $object )

Returns the status for the specified tidy object.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Esempi

Example #1 tidy::getStatus() example

<?php
$html 
'<p>paragraph</i>';
$tidy = new tidy();
$tidy->parseString($html);

$tidy2 = new tidy();
$html2 '<bogus>test</bogus>';
$tidy2->parseString($html2);

echo 
$tidy->getStatus(); //1

echo $tidy2->getStatus(); //2
?>



tidy::head

tidy_get_head

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::head -- tidy_get_headReturns a tidyNode object starting from the <head> tag of the tidy parse tree

Descrizione

Stile orientato agli oggetti

tidyNode tidy::head ( void )

Stile procedurale

tidyNode tidy_get_head ( tidy $object )

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns the tidyNode object.

Esempi

Example #1 tidy::head() example

<?php
$html 
'
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>'
;

$tidy tidy_parse_string($html);

$head $tidy->head();
echo 
$head->value;
?>

Il precedente esempio visualizzerà:

<head>
<title>test</title>
</head>

Note

Nota: Questa funzione è disponibile solo con Zend Engine 2 (PHP >= 5.0.0).

Vedere anche:

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree


tidy::html

tidy_get_html

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::html -- tidy_get_htmlReturns a tidyNode object starting from the <html> tag of the tidy parse tree

Descrizione

Stile orientato agli oggetti

tidyNode tidy::html ( void )

Stile procedurale

tidyNode tidy_get_html ( tidy $object )

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

Returns the tidyNode object.

Esempi

Example #1 tidy::html() example

<?php
$html 
'
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>'
;

$tidy tidy_parse_string($html);

$html $tidy->html();
echo 
$html->value;
?>

Il precedente esempio visualizzerà:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Note

Nota: Questa funzione è disponibile solo con Zend Engine 2 (PHP >= 5.0.0).

Vedere anche:

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree


tidy::isXhtml

tidy_is_xhtml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtmlIndicates if the document is a XHTML document

Descrizione

Stile orientato agli oggetti

bool tidy::isXhtml ( void )

Stile procedurale

bool tidy_is_xhtml ( tidy $object )

Tells if the document is a XHTML document.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Avviso

This function is not yet implemented in the Tidylib itself, so it always return FALSE.



tidy::isXml

tidy_is_xml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xmlIndicates if the document is a generic (non HTML/XHTML) XML document

Descrizione

Stile orientato agli oggetti

bool tidy::isXml ( void )

Stile procedurale

bool tidy_is_xml ( tidy $object )

Tells if the document is a generic (non HTML/XHTML) XML document.

Elenco dei parametri

object

L'oggetto Tidy

Valori restituiti

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Avviso

This function is not yet implemented in the Tidylib itself, so it always return FALSE.



tidy::parseFile

tidy_parse_file

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_fileParse markup in file or URI

Descrizione

Stile orientato agli oggetti

bool tidy::parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Stile procedurale

tidy tidy_parse_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Parses the given file.

Elenco dei parametri

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, see » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Example #1 tidy::parseFile() example

<?php
$tidy 
= new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty(
$tidy->errorBuffer)) {
    echo 
"The following errors or warnings occurred:\n";
    echo 
$tidy->errorBuffer;
}
?>

Note

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

Vedere anche:



tidy::parseString

tidy_parse_string

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_stringParse a document stored in a string

Descrizione

Stile orientato agli oggetti

bool tidy::parseString ( string $input [, mixed $config [, string $encoding ]] )

Stile procedurale

tidy tidy_parse_string ( string $input [, mixed $config [, string $encoding ]] )

Parses a document stored in a string.

Elenco dei parametri

input

The data to be parsed.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Valori restituiti

Returns a new tidy instance.

Esempi

Example #1 tidy::parseString() example

<?php
ob_start
();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer 
ob_get_clean();
$config = array('indent' => TRUE,
                
'output-xhtml' => TRUE,
                
'wrap' => 200);

$tidy tidy_parse_string($buffer$config'UTF8');

$tidy->cleanRepair();
echo 
$tidy;
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

Note

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

Vedere anche:



tidy::repairFile

tidy_repair_file

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_fileRepair a file and return it as a string

Descrizione

Stile orientato agli oggetti

string tidy::repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Stile procedurale

string tidy_repair_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Repairs the given file and returns it as a string.

Elenco dei parametri

filename

The file to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Valori restituiti

Returns the repaired contents as a string.

Esempi

Example #1 tidy::repairFile() example

<?php
$file 
'file.html';

$tidy = new tidy();
$repaired $tidy->repairfile($file);
rename($file$file '.bak');

file_put_contents($file$repaired);
?>

Note

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

Vedere anche:



tidy::repairString

tidy_repair_string

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_stringRepair a string using an optionally provided configuration file

Descrizione

Stile orientato agli oggetti

string tidy::repairString ( string $data [, mixed $config [, string $encoding ]] )

Stile procedurale

string tidy_repair_string ( string $data [, mixed $config [, string $encoding ]] )

Repairs the given string.

Elenco dei parametri

data

The data to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check » http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: