{
    "slug": "php_simplexml",
    "term": "SimpleXML — Parsing XML in PHP",
    "category": "php",
    "difficulty": "beginner",
    "short": "SimpleXML provides the fastest way to read well-formed XML in PHP — simplexml_load_string() or simplexml_load_file() returns an object where elements are properties and attributes are array-accessed, requiring no tree traversal.",
    "long": "SimpleXML represents an XML document as a PHP object where child elements are accessed as object properties and attributes as array keys. Accessing a missing element returns an empty SimpleXMLElement (not null), so boolean checks need care. SimpleXML is ideal for consuming simple XML APIs and configuration files. For namespace-aware XML, use children() and attributes() with the namespace URI. SimpleXML and DOMDocument are interoperable: simplexml_import_dom() and dom_import_simplexml() convert between them. For complex queries, convert to DOMDocument and use XPath. SimpleXML cannot handle very large files — it loads the entire document into memory.",
    "aliases": [
        "SimpleXML",
        "simplexml_load_string",
        "simplexml_load_file",
        "PHP XML"
    ],
    "tags": [
        "php-stdlib",
        "xml",
        "api-consumption",
        "rss",
        "soap"
    ],
    "misconception": "Checking 'if ($xml->element)' correctly tests for element existence. An absent element returns an empty SimpleXMLElement which is truthy. Use isset($xml->element) or count($xml->element) > 0 to test for existence.",
    "why_it_matters": "Many legacy and enterprise APIs — SOAP, RSS/Atom feeds, OpenDocument formats, configuration files — use XML. SimpleXML is the fastest way to consume them in PHP without writing tree traversal code. Understanding when to reach for SimpleXML versus DOMDocument versus XMLReader saves significant time.",
    "common_mistakes": [
        "Not casting SimpleXMLElement to string/int when using values — concatenation and arithmetic on a SimpleXMLElement object can produce unexpected results.",
        "Using foreach on a potentially single-element result — SimpleXML returns a single SimpleXMLElement for one child and an iterable for multiple; always use foreach safely.",
        "Loading untrusted external XML with libxml_disable_entity_loader(false) — XML External Entity (XXE) attacks are possible if external entities are enabled.",
        "Ignoring namespace prefixes — xml:lang, atom:title and other namespaced attributes are invisible to property access; use attributes('ns', true) for namespace-aware access."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "php_dom_xpath",
        "xxe",
        "xml_injection",
        "curl_functions"
    ],
    "prerequisites": [],
    "refs": [
        "https://www.php.net/SimpleXML",
        "https://www.php.net/simplexml_load_string"
    ],
    "bad_code": "<?php\n// ❌ Naive SimpleXML usage — wrong existence check, no error handling\n$xml = simplexml_load_string($apiResponse);\n\nif ($xml->error) { // Wrong — empty element is truthy!\n    handleError();\n}\n\n// Forgetting to cast types\n$count = $xml->results->count; // SimpleXMLElement, not int\nfor ($i = 0; $i < $count; $i++) { // May behave unexpectedly\n    // ...\n}",
    "good_code": "<?php\n// ✅ Correct SimpleXML usage\nlibxml_use_internal_errors(true);\n$xml = simplexml_load_string($apiResponse);\n\nif ($xml === false) {\n    $errors = libxml_get_errors();\n    libxml_clear_errors();\n    throw new RuntimeException('Invalid XML: ' . $errors[0]->message);\n}\n\n// Correct existence check\nif (isset($xml->error)) {\n    handleError((string) $xml->error->message);\n}\n\n// Always cast to PHP types\n$count = (int) $xml->results->count;\n$title = (string) $xml->title;\n\n// Namespace-aware access\n$ns = $xml->children('http://www.w3.org/2005/Atom');\nforeach ($ns->entry as $entry) {\n    echo (string) $entry->title;\n}",
    "quick_fix": "Use libxml_use_internal_errors(true) before loading to handle malformed XML gracefully, then check libxml_get_errors() to decide whether to proceed or reject the input.",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_simplexml",
        "html_url": "https://codeclaritylab.com/glossary/php_simplexml",
        "json_url": "https://codeclaritylab.com/glossary/php_simplexml.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[SimpleXML — Parsing XML in PHP](https://codeclaritylab.com/glossary/php_simplexml) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_simplexml"
            }
        }
    }
}