Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> PHP

PHP Arrays Store करना: json_encode vs serialize


PHP arrays को store/serialize करने के दो मुख्य तरीके: json_encode() और serialize()। प्रत्येक के अपने फायदे हैं।

त्वरित तुलना

पहलूjson_encode()serialize()
Portability✅ Universal (JS, Python, आदि)❌ केवल PHP
Performanceतेज़ (usually)धीमा (complex structures के लिए)
Object Supportकेवल public properties → stdClass✅ Full class + private/protected
Nested Arraysअच्छाबेहतर (deep nesting के लिए)
ReadabilityHuman-readableनहीं (binary-like)
UnicodeJSON_UNESCAPED_UNICODE के साथ अच्छाNative support

json_encode() - जब उपयोग करें

<?php
$array = [
    'name' => 'अमित',
    'email' => 'amit@example.com',
    'tags' => ['php', 'developer'],
    'metadata' => (object)['created' => '2024-01-15']
];

// Basic
$json = json_encode($array);

// Unicode support (हिंदी, इमोजी के लिए)
$json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// Pretty print (debugging के लिए)
$json = json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Decode back
$restored = json_decode($json, true); // true = associative array

// Output: {"name":"अमित","email":"amit@example.com","tags":["php","developer"],"metadata":{"created":"2024-01-15"}}

serialize() - जब उपयोग करें

<?php
class User {
    public $name;
    private $email;
    protected $role;
    
    public function __construct($name, $email, $role) {
        $this->name = $name;
        $this->email = $email;
        $this->role = $role;
    }
    
    // Sleep/wakeup for custom serialization
    public function __sleep() {
        return ['name', 'email', 'role']; // Only these properties
    }
    
    public function __wakeup() {
        // Reinitialize connections, etc.
    }
}

$user = new User('अमित', 'amit@example.com', 'admin');
$serialized = serialize($user);
// Output: O:4:"User":3:{s:4:"name";s:6:"अमित";s:11:"Useremail";s:18:"amit@example.com";s:7:"Userrole";s:5:"admin";}

// Restore - class definition must be available
$restored = unserialize($serialized);

Decision Matrix

ScenarioRecommended
API responses, config files, cachejson_encode()
Database storage (portability)json_encode()
Session data (PHP native)serialize() (PHP does automatically)
Complex objects with private propsserialize()
Inter-service communicationjson_encode()
Deep nesting (100+ levels)serialize()
Legacy PHP (< 5.2) compatibilityserialize()

Performance Benchmark (10k elements)

// Typical results:
json_encode:     ~3ms encode, ~2ms decode
serialize:       ~5ms encode, ~4ms unserialize
// JSON usually faster for simple structures

Hybrid Approach: Best of Both

<?php
function smartEncode($data) {
    // Objects के लिए serialize, arrays/scalars के लिए JSON
    if (is_object($data) && !($data instanceof \JsonSerializable)) {
        return ['__php_serialize' => true, 'data' => base64_encode(serialize($data))];
    }
    return ['__php_serialize' => false, 'data' => $data];
}

function smartDecode($wrapper) {
    if ($wrapper['__php_serialize']) {
        return unserialize(base64_decode($wrapper['data']));
    }
    return $wrapper['data'];
}

// JSON में store करें
$stored = json_encode(smartEncode($complexData), JSON_UNESCAPED_UNICODE);
// Retrieve
$data = smartDecode(json_decode($stored, true));

सुरक्षा नोट

अविश्वसनीय डेटा पर unserialize() कभी न चलाएं! यह Object Injection vulnerabilities (POP chains) का कारण बन सकता है। हमेशा json_decode() उपयोग करें external data के लिए। यदि unserialize() आवश्यक है, तो allowed_classes विकल्प उपयोग करें (PHP 7+):

$data = unserialize($input, ['allowed_classes' => ['MyClass', 'DateTime']]);
  1. JavaScript JSON parse() मेथड JavaScript JSON parse() मेथड

    JSON parse() मेथड का उपयोग JSON स्ट्रिंग को पार्स करने और उससे JavaScript ऑब्जेक्ट बनाने के लिए किया जाता है। उदाहरण <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initi

  1. JavaScript JSON Arrays JavaScript JSON Arrays

    JSON में Arrays, JavaScript में Arrays के समान होते हैं। JavaScript JSON arrays इस तरह दिखते हैं: let obj = {    name:'Rohan',    sports : ['cricket','Football','volleyball','hockey'] } JavaScript में JSON arrays के लिए कोड: उदाहरण <!DOC

  1. - C# सरणियों में TrueForAll() विधि

    TrueForAll() विधि के साथ सरणियों में, आप प्रत्येक तत्व को किसी शर्त के लिए जांच सकते हैं। आइए एक उदाहरण देखें: उदाहरण 1); Console.WriteLine(result); } } आउटपुट True TrueForAll() विधि के साथ सरणियों में, आप प्रत्येक तत्व को किसी शर्त के लिए जांच सकते हैं। आइए एक उदाहरण देखें: उदाहरण