DOMDocument example

/** * Constructor. * * @throws BadMethodCallException */
    public function __construct()
    {
        if (extension_loaded('DOM')) {
            throw new BadMethodCallException('DOM extension is required, but not currently loaded.'); // @codeCoverageIgnore         }

        $this->dom = new DOMDocument('1.0', 'utf-8');
    }

    /** * Returns the body of the current document. */
    public function getBody(): string
    {
        return $this->dom->saveHTML();
    }

    /** * Sets a string as the body that we want to work with. * * @return $this */
public function __construct(SimplePie_File $file$timeout = 10, $useragent = null, $max_checked_feeds = 10, $force_fsockopen = false, $curl_options = array())
    {
        $this->file = $file;
        $this->useragent = $useragent;
        $this->timeout = $timeout;
        $this->max_checked_feeds = $max_checked_feeds;
        $this->force_fsockopen = $force_fsockopen;
        $this->curl_options = $curl_options;

        if (class_exists('DOMDocument') && $this->file->body != '')
        {
            $this->dom = new DOMDocument();

            set_error_handler(array('SimplePie_Misc', 'silence_errors'));
            try
            {
                $this->dom->loadHTML($this->file->body);
            }
            catch (Throwable $ex)
            {
                $this->dom = null;
            }
            restore_error_handler();
        }

    public function addXmlContent(string $content, string $charset = 'UTF-8', int $options = \LIBXML_NONET)
    {
        // remove the default namespace if it's the only namespace to make XPath expressions simpler         if (!str_contains($content, 'xmlns:')) {
            $content = str_replace('xmlns', 'ns', $content);
        }

        $internalErrors = libxml_use_internal_errors(true);

        $dom = new \DOMDocument('1.0', $charset);
        $dom->validateOnParse = true;

        if ('' !== trim($content)) {
            @$dom->loadXML($content$options);
        }

        libxml_use_internal_errors($internalErrors);

        $this->addDocument($dom);

        $this->isHtml = false;
    }
/** * XML descriptor. * * @author Jean-François Simon <contact@jfsimon.fr> * * @internal */
class XmlDescriptor extends Descriptor
{
    public function getInputDefinitionDocument(InputDefinition $definition): \DOMDocument
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->appendChild($definitionXML = $dom->createElement('definition'));

        $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
        foreach ($definition->getArguments() as $argument) {
            $this->appendDocument($argumentsXML$this->getInputArgumentDocument($argument));
        }

        $definitionXML->appendChild($optionsXML = $dom->createElement('options'));
        foreach ($definition->getOptions() as $option) {
            $this->appendDocument($optionsXML$this->getInputOptionDocument($option));
        }

        
// Check if the supplied URL is a feed, if it isn't, look for it.             $locate = $this->registry->create('Locator', array(&$file$this->timeout, $this->useragent, $this->max_checked_feeds, $this->force_fsockopen, $this->curl_options));

            if (!$locate->is_feed($file))
            {
                $copyStatusCode = $file->status_code;
                $copyContentType = $file->headers['content-type'];
                try
                {
                    $microformats = false;
                    if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
                        $doc = new DOMDocument();
                        @$doc->loadHTML($file->body);
                        $xpath = new DOMXpath($doc);
                        // Check for both h-feed and h-entry, as both a feed with no entries                         // and a list of entries without an h-feed wrapper are both valid.                         $query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
                            'contains(concat(" ", @class, " "), " h-entry ")]';
                        $result = $xpath->query($query);
                        $microformats = $result->length !== 0;
                    }
                    // Now also do feed discovery, but if microformats were found don't                     // overwrite the current value of file.
protected function assertXpathNodeValue(\DOMElement $element$expression$nodeValue)
    {
        $xpath = new \DOMXPath($element->ownerDocument);
        $nodeList = $xpath->evaluate($expression);
        $this->assertEquals(1, $nodeList->length);
        $this->assertEquals($nodeValue$nodeList->item(0)->nodeValue);
    }

    protected function assertMatchesXpath($html$expression$count = 1)
    {
        $dom = new \DOMDocument('UTF-8');

        $html = preg_replace('/(<input [^>]+)(?<!\/)>/', '$1/>', $html);

        try {
            // Wrap in <root> node so we can load HTML with multiple tags at             // the top level             $dom->loadXML('<root>'.$html.'</root>');
        } catch (\Exception $e) {
            $this->fail(sprintf(
                "Failed loading HTML:\n\n%s\n\nError: %s",
                $html,
                
/** * @see http://github.com/zendframework/zend-diactoros for the canonical source repository * * @author Fábio Pacheco * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License */
    public static function ianaCodesReasonPhrasesProvider()
    {
        // XML taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xml         // (might not be up-to-date for older Symfony versions)         $ianaHttpStatusCodes = new \DOMDocument();
        $ianaHttpStatusCodes->load(__DIR__.'/Fixtures/xml/http-status-codes.xml');
        if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) {
            self::fail('Invalid IANA\'s HTTP status code list.');
        }

        $ianaCodesReasonPhrases = [];

        $xpath = new \DOMXPath($ianaHttpStatusCodes);
        $xpath->registerNamespace('ns', 'http://www.iana.org/assignments');

        $records = $xpath->query('//ns:record');
        


  /** * Tests Html::serialize(). * * Resolves an issue by where an empty DOMDocument object sent to serialization would * cause errors in getElementsByTagName() in the serialization function. * * @covers ::serialize */
  public function testSerialize() {
    $document = new \DOMDocument();
    $result = Html::serialize($document);
    $this->assertSame('', $result);
  }

  /** * @covers ::transformRootRelativeUrlsToAbsolute * @dataProvider providerTestTransformRootRelativeUrlsToAbsolute */
  public function testTransformRootRelativeUrlsToAbsolute($html$scheme_and_host$expected_html) {
    $this->assertSame($expected_html ?: $html, Html::transformRootRelativeUrlsToAbsolute($html$scheme_and_host));
  }

  

        if ($this->_elementMap === null) {
            $dataToInsert = $event;
        } else {
            $dataToInsert = array();
            foreach ($this->_elementMap as $elementName => $fieldKey) {
                $dataToInsert[$elementName] = $event[$fieldKey];
            }
        }

        $enc = $this->getEncoding();
        $dom = new DOMDocument('1.0', $enc);
        $elt = $dom->appendChild(new DOMElement($this->_rootElement));

        foreach ($dataToInsert as $key => $value) {
            if (empty($value) 
                || is_scalar($value) 
                || (is_object($value) && method_exists($value,'__toString'))
            ) {
                if($key == "message") {
                    $value = htmlspecialchars($value, ENT_COMPAT, $enc);
                }
                $elt->appendChild(new DOMElement($key(string)$value));
            }
$count++;
    }
  }

  /** * Returns a view output as SimpleXMLElement. * * @return \SimpleXMLElement|null * The HTML DOM. */
  protected function getHtmlDom($output) {
    $html_dom = new \DOMDocument();
    @$html_dom->loadHTML($output);
    if ($html_dom) {
      // It's much easier to work with simplexml than DOM, luckily enough       // we can just simply import our DOM tree.       return simplexml_import_dom($html_dom);
    }
    return NULL;
  }

}
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Util\XliffUtils;

class TranslationFilesTest extends TestCase
{
    /** * @dataProvider provideTranslationFiles */
    public function testTranslationFileIsValid($filePath)
    {
        $document = new \DOMDocument();
        $document->loadXML(file_get_contents($filePath));

        $errors = XliffUtils::validateSchema($document);

        $this->assertCount(0, $errorssprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message'))));
    }

    /** * @dataProvider provideTranslationFiles * * @group Legacy */
/** * @package content * * @internal * * @covers \Shopware\Core\System\CustomEntity\Xml\Config\AdminUi\XmlElements\Detail */
class DetailTest extends TestCase
{
    public function testFromXml(): void
    {
        $dom = new \DOMDocument();
        $detailElement = $dom->createElement('detail');
        $tabsElement = $dom->createElement('tabs');

        $detailElement->appendChild(
            $tabsElement
        );

        $detail = Detail::fromXml($detailElement);
        static::assertInstanceOf(Detail::class$detail);

        $tabs = $detail->getTabs();
        
class FormTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        // Ensure that the private helper class FormFieldRegistry is loaded         class_exists(Form::class);
    }

    public function testConstructorThrowsExceptionIfTheNodeHasNoFormAncestor()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML(' <html> <input type="submit" /> <form> <input type="foo" /> </form> <button /> </html> ');

        $nodes = $dom->getElementsByTagName('input');

        

        ],
        '#access' => FALSE,
      ],
    ];

    // Start with a fresh copy of the base array, and try rendering the entire     // thing. We expect a single <ul> with appropriate links contained within     // it.     $render_array = $base_array;
    $html = \Drupal::service('renderer')->renderRoot($render_array);
    $dom = new \DOMDocument();
    $dom->loadHTML($html);
    $this->assertEquals(1, $dom->getElementsByTagName('ul')->length, 'One "ul" tag found in the rendered HTML.');
    $list_elements = $dom->getElementsByTagName('li');
    $this->assertEquals(3, $list_elements->length, 'Three "li" tags found in the rendered HTML.');
    $this->assertEquals('Parent link original', $list_elements->item(0)->nodeValue, 'First expected link found.');
    $this->assertEquals('First child link', $list_elements->item(1)->nodeValue, 'Second expected link found.');
    $this->assertEquals('Second child link', $list_elements->item(2)->nodeValue, 'Third expected link found.');
    $this->assertStringNotContainsString('Parent link copy', $html, '"Parent link copy" link not found.');
    $this->assertStringNotContainsString('Third child link', $html, '"Third child link" link not found.');

    // Now render 'first_child', followed by the rest of the links, and make
$phpunitConfigFilename = $getPhpUnitConfig($argv[$cliArgumentIndex + 1]);
                } else {
                    $phpunitConfigFilename = $getPhpUnitConfig(substr($cliArgument, 2));
                }
                break;
            }
        }

        $phpunitConfigFilename = $phpunitConfigFilename ?: $getPhpUnitConfig('phpunit.xml');

        if ($phpunitConfigFilename) {
            $phpunitConfig = new DOMDocument();
            $phpunitConfig->load($phpunitConfigFilename);
        } else {
            $phpunitConfig = false;
        }
    }
    if (false !== $phpunitConfig) {
        $var = new DOMXPath($phpunitConfig);
        foreach ($var->query('//php/server[@name="'.$name.'"]') as $var) {
            return $var->getAttribute('value');
        }
        foreach ($var->query('//php/env[@name="'.$name.'"]') as $var) {
            
Home | Imprint | This part of the site doesn't use cookies.