Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php parse xml

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
Comment

php xml parser

$xmlContent = file_get_contents(__DIR__ . '/myFile.xml');
$contentToObject = new SimpleXMLElement($xmlContent);
$jsonData = json_encode($contentToObject, JSON_UNESCAPED_SLASHES);
Comment

PHP XML Expat Parser

<?php
// Initialize the XML parser
$parser=xml_parser_create();

// Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
  switch($element_name) {
    case "NOTE":
    echo "-- Note --<br>";
    break;
    case "TO":
    echo "To: ";
    break;
    case "FROM":
    echo "From: ";
    break;
    case "HEADING":
    echo "Heading: ";
    break;
    case "BODY":
    echo "Message: ";
  }
}

// Function to use at the end of an element
function stop($parser,$element_name) {
  echo "<br>";
}

// Function to use when finding character data
function char($parser,$data) {
  echo $data;
}

// Specify element handler
xml_set_element_handler($parser,"start","stop");

// Specify data handler
xml_set_character_data_handler($parser,"char");

// Open XML file
$fp=fopen("note.xml","r");

// Read data
while ($data=fread($fp,4096)) {
  xml_parse($parser,$data,feof($fp)) or
  die (sprintf("XML Error: %s at line %d",
  xml_error_string(xml_get_error_code($parser)),
  xml_get_current_line_number($parser)));
}

// Free the XML parser
xml_parser_free($parser);
?>
Comment

php xml parser

## Usage

use TiagoFrancaHelpersXmlXmlHandler;

$xmlContent = file_get_contents(__DIR__ . '/myFile.xml');
$data = (new XmlHandler())->toArray($xmlContent);
// $data = XmlHandler::toArray($xmlContent);
var_dump($data);

### Class here
<?php

namespace TiagoFrancaHelpersXml;

use SimpleXMLElement;
use BadMethodCallException;

class XmlHandler
{
    public const UNAVAILABLE_FUNCTIONS = [
        // 'toArray',
    ];

    public const AVAILABLE_FUNCTIONS = [
        'parse',
        'toJson',
        'toObject',
        'toArray',
    ];

    /**
     * xmlParse function
     *
     * @param string|null $xmlContent
     * @return SimpleXMLElement|null
     */
    public static function xmlParse(?string $xmlContent): ?SimpleXMLElement
    {
        if (!$xmlContent) {
            return null;
        }

        return new SimpleXMLElement($xmlContent);
    }

    /**
     * xmlToJson function
     *
     * @param string|SimpleXMLElement|null $xmlContent
     * @param integer $flags json_encode $flags
     * @param integer $depth json_encode $depth
     * @return string|null
     */
    public static function xmlToJson(
        string|SimpleXMLElement|null $xmlContent,
        int $flags = 0,
        int $depth = 512
    ): ?string {
        if (!$xmlContent) {
            return null;
        }

        $xmlContent = is_string($xmlContent) ? static::xmlParse($xmlContent) : $xmlContent;

        return json_encode($xmlContent, $flags, $depth) ?: null;
    }

    /**
     * function xmlToObject
     *
     * @param string|SimpleXMLElement|null $xmlContent
     * @return object|null
     */
    public static function xmlToObject(string|SimpleXMLElement|null $xmlContent): ?object
    {
        $xmlContent = static::xmlToJson($xmlContent ?: null);

        if (!$xmlContent) {
            return null;
        }

        return json_decode($xmlContent, false);
    }

    /**
     * function xmlToArray
     *
     * @param string|SimpleXMLElement|null $xmlContent
     * @return array|null
     */
    public static function xmlToArray(string|SimpleXMLElement|null $xmlContent): ?array
    {
        $xmlContent = static::xmlToJson($xmlContent ?: null);

        if (!$xmlContent) {
            return null;
        }

        return json_decode($xmlContent, true);
    }

    public function __call(string $method, array $arguments): mixed
    {
        if (
            !in_array($method, static::AVAILABLE_FUNCTIONS)
            ||
            in_array($method, static::UNAVAILABLE_FUNCTIONS)
        ) {
            throw new BadMethodCallException("Invalid method: ${method}");
        }

        $methodToCall = 'xml' . ucfirst($method);

        if (in_array($methodToCall, static::UNAVAILABLE_FUNCTIONS)) {
            throw new BadMethodCallException("Invalid method: ${method}");
        }

        return call_user_func_array(
            static::class . '::' . $methodToCall,
            $arguments
        );
    }

    public static function __callStatic(string $method, array $arguments)
    {
        $availableMethods = static::availableFunctions();

        if (!in_array($method, $availableMethods)) {
            throw new BadMethodCallException("Invalid method: ${method}");
        }

        return (new static())->__call($method, $arguments);
    }

    /**
     * function availableFunctions
     *
     * @return array|null
     */
    public static function availableFunctions(): ?array
    {
        $allMethods = array_values(
            array_unique(
                array_merge(
                    get_class_methods(static::class),
                    static::AVAILABLE_FUNCTIONS
                )
            )
        );

        return array_filter(
            $allMethods,
            fn ($functionName) => !in_array($functionName, static::UNAVAILABLE_FUNCTIONS)
        );
    }
}
Comment

PREVIOUS NEXT
Code Example
Php :: php length of array 
Php :: laravel migrate only new tables 
Php :: get first 200 characters string php 
Php :: php import function from another file 
Php :: what sign is less than or equal to php 
Php :: select session php 
Php :: console.log in php 
Php :: laravel route is current route 
Php :: stream_set_blocking 
Php :: check php version 
Php :: laravel required if another field has value 
Php :: remove special character in php 
Php :: composer require laravel/ui laravel 7 
Php :: valid number in excel php 
Php :: get params from url php 
Php :: php access json object 
Php :: Message: Too few arguments to function Admin::tindakan_vaksin1(), 1 passed in C:xampphtdocsloginsystemcoreCodeIgniter.php on line 532 and exactly 2 expected 
Php :: php variable outside foreach 
Php :: PHP str_shuffle — Randomly shuffles a string 
Php :: php str_pad not working 
Php :: bindings laravel 
Php :: how to take input in php 
Php :: blade template vs php core 
Php :: webstorm vs phpstorm 
Php :: php ini_set timeout 
Php :: how to add woocommerce cart counter 
Php :: push element at tart of arrray php 
Php :: php date fomat 
Php :: laravel migration add date of birth column 
Php :: laravel print query with parameters 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =