Tag Archives: php

Đọc các dòng của file ra mảng

Kiểu truyền thống!
$arrLines = file(‘/home/huypv/xxx.txt’);
Ưu điểm: Dễ nhớ
Hạn chế: Có thể gặp problem với kí tự \r, \n, dòng trống

Đọc pro hơn
$arrLines = file(‘/home/huypv/xxx.txt’, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Ưu điểm: \r, \n đã biến mất, dòng trống được bỏ qua
Hạn chế: Phải nhớ tên hằng số FILE_???

Sắp xếp mảng theo cách bạn thích

<?php
    $arr = array(
        array('name' => 'n4', 'value' => 'v1'),
        array('name' => 'n5', 'value' => 'v2'),
        array('name' => 'n3', 'value' => 'v3'),
    );

    usort($arr, array("Comp", "mycmp"));
    class Comp {
        function mycmp($e1, $e2) {
            return strcmp($e1['name'], $e2['name']);
        }
    }
    print_r($arr);
?>

xdebug not loaded as zend extension

I hate error, of course.
And I hate warning too.
How to fix this warning ^^ when using xdebug
Windows: Edit file php.ini (xác định đường dẫn file php.ini đã load = cách: gõ php –ini với php-cli, và tạo file phpinfo() với php-cgi)
[Xdebug]
zend_extension_ts=”C:/php/ext/php_xdebug.dll”

Còn cứ để comment dòng
;extension=php_xdebug.dll

Linux: xdebug.ini (ví dụ /etc/php.d/xdebug.ini)
zend_extension_ts=/usr/lib64/php/modules/xdebug.so
Và comment dòng
;extension=xdebug.so

Cơ bản việc dùng DOM xử lý XML,HTML trong PHP

$dom = new domDocument(‘1.0’, ‘utf-8’);
$content = file_get_contents(‘weather.htm’);
$content = mb_convert_encoding($content, ‘HTML-ENTITIES’, “UTF-8”);
@$dom->loadHTML($content);
/*$xpath = new DOMXPath($dom);
$ele = $xpath->query(‘//table’);
echo $ele->item(0)->nodeName;*/
$dom->preserveWhiteSpace = false;

$dom->getElementsByTagName(‘table’);
$dom->getElementById(‘player’);

$ele->parentNode
$ele->childNodes->item(0)
$ele->getAttribute(‘src’);
$ele->nodeValue;
…

Using cURL to download file

<?php
    function getContents($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
    
    function downloadFile($url, $path, $file) {
        //if (!file_exists($path)) mkdir($path, 0755, true);
        $filePath = $path . ‘/’ . $file;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $fp = fopen($filePath, “wb”);
        $options = array(
                CURLOPT_URL => $url,                    
                CURLOPT_FOLLOWLOCATION => 1,
                CURLOPT_FILE => $fp);

        curl_setopt_array($ch, $options);
                
        curl_exec($ch);    
        curl_close($ch);
        fclose($fp);
    }