SimpleXMLElement example

if ($locale->getLocale() !== 'de_DE') {
            $lang = 'en';
        }

        $result = [];

        $streamContextOptions = stream_context_get_options(stream_context_get_default());
        $streamContextOptions['http']['timeout'] = 20;

        try {
            $xml = new SimpleXMLElement(
                file_get_contents(
                    'https://' . $lang . '.shopware.com/news/?sRss=1',
                    false,
                    stream_context_create($streamContextOptions)
                )
            );
        } catch (Exception $e) {
            return [];
        }

        foreach ($xml->channel->item as $news) {
            
use Shopware\Core\Framework\Log\Package;

#[Package('system-settings')] class XmlFileWriter extends AbstractFileWriter
{
    public function append(Config $config, array $data, int $index): void
    {
        if ($index === 0) {
            fwrite($this->buffer, "<?xml version=\"1.0\"?><root>\n");
        }

        $item = new \SimpleXMLElement('<item/>');
        $this->addDataToNode($item$data);
        /** @var string $xml */
        $xml = mb_strstr($item->asXML(), '<item>');
        fwrite($this->buffer, $xml);
    }

    public function finish(Config $config, string $targetPath): void
    {
        fwrite($this->buffer, "</root>\n");
        parent::finish($config$targetPath);
    }

    

        'test_id' => 23,
        'test_class' => 'Drupal\Tests\simpletest\Unit\TestDiscoveryTest',
        'status' => 'pass',
        'message' => '',
        'message_group' => 'Other',
        'function' => 'Drupal\Tests\simpletest\Unit\TestDiscoveryTest->testGetTestClasses()',
        'line' => 108,
        'file' => '/Users/paul/projects/drupal/core/modules/simpletest/tests/src/Unit/TestDiscoveryTest.php',
      ],
    ];
    $this->assertEquals($simpletest, JUnitConverter::xmlElementToRows(23, new \SimpleXMLElement($junit)));
  }

  /** * @covers ::convertTestCaseToSimpletestRow */
  public function testConvertTestCaseToSimpletestRow() {
    $junit = <<<EOD <testcase name="testGetTestClasses" class="Drupal\Tests\simpletest\Unit\TestDiscoveryTest" classname="Drupal.Tests.simpletest.Unit.TestDiscoveryTest" file="/Users/paul/projects/drupal/core/modules/simpletest/tests/src/Unit/TestDiscoveryTest.php" line="108" assertions="2" time="0.100787"/> EOD;
    $simpletest = [
      'test_id' => 23,
      
function extractLocaleFromFilePath($filePath)
{
    $parts = explode('.', $filePath);

    return $parts[count($parts) - 2];
}

function extractTranslationKeys($filePath): array
{
    $translationKeys = [];
    $contents = new \SimpleXMLElement(file_get_contents($filePath));

    foreach ($contents->file->body->{'trans-unit'} as $translationKey) {
        $translationId = (string) $translationKey['id'];
        $translationKey = (string) $translationKey->source;

        $translationKeys[$translationId] = $translationKey;
    }

    return $translationKeys;
}


function _oembed_create_xml( $data$node = null ) {
    if ( ! is_array( $data ) || empty( $data ) ) {
        return false;
    }

    if ( null === $node ) {
        $node = new SimpleXMLElement( '<oembed></oembed>' );
    }

    foreach ( $data as $key => $value ) {
        if ( is_numeric( $key ) ) {
            $key = 'oembed';
        }

        if ( is_array( $value ) ) {
            $item = $node->addChild( $key );
            _oembed_create_xml( $value$item );
        } else {
            

  public static function xmlToRows($test_id$phpunit_xml_file) {
    $contents = @file_get_contents($phpunit_xml_file);
    if (!$contents) {
      return [];
    }
    return static::xmlElementToRows($test_idnew \SimpleXMLElement($contents));
  }

  /** * Parse test cases from XML to {simpletest} schema. * * @param int $test_id * The current test ID. * @param \SimpleXMLElement $element * The XML data from the JUnit file. * * @return array[] * The results as array of rows in a format that can be inserted into the * {simpletest} table of the results database. * * @internal */

        'name' => "#type 'more_link' anchor tag to the front page",
        'value' => [
          '#type' => 'more_link',
          '#url' => Url::fromRoute('<front>'),
        ],
        'expected' => '//div[@class="more-link"]/a[@href="' . Url::fromRoute('<front>')->toString() . '" and text()="More"]',
      ],
    ];

    foreach ($elements as $element) {
      $xml = new \SimpleXMLElement(\Drupal::service('renderer')->renderRoot($element['value']));
      $result = $xml->xpath($element['expected']);
      $this->assertNotEmpty($result, '"' . $element['name'] . '" input rendered correctly.');
    }
  }

  /** * Tests system #type 'system_compact_link'. */
  public function testSystemCompactLink() {
    $elements = [
      [
        

  protected function parseXml($raw_xml) {
    try {
      $xml = new \SimpleXMLElement($raw_xml);
    }
    catch (\Exception $e) {
      // SimpleXMLElement::__construct produces an E_WARNING error message for       // each error found in the XML data and throws an exception if errors       // were detected. Catch any exception and return failure (NULL).       return NULL;
    }
    // If there is no valid project data, the XML is invalid, so return failure.     if (!isset($xml->short_name)) {
      return NULL;
    }
    


    /** * Gets XML for a sitemap index. * * @since 5.5.0 * * @param array $sitemaps Array of sitemap URLs. * @return string|false A well-formed XML string for a sitemap index. False on error. */
    public function get_sitemap_index_xml( $sitemaps ) {
        $sitemap_index = new SimpleXMLElement(
            sprintf(
                '%1$s%2$s%3$s',
                '<?xml version="1.0" encoding="UTF-8" ?>',
                $this->stylesheet_index,
                '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />'
            )
        );

        foreach ( $sitemaps as $entry ) {
            $sitemap = $sitemap_index->addChild( 'sitemap' );

            

class Zend_Config_Writer_Xml extends Zend_Config_Writer_FileAbstract
{
    /** * Render a Zend_Config into a XML config string. * * @since 1.10 * @return string */
    public function render()
    {
        $xml         = new SimpleXMLElement('<zend-config xmlns:zf="' . Zend_Config_Xml::XML_NAMESPACE . '"/>');
        $extends     = $this->_config->getExtends();
        $sectionName = $this->_config->getSectionName();

        if (is_string($sectionName)) {
            $child = $xml->addChild($sectionName);

            $this->_addBranch($this->_config, $child$xml);
        } else {
            foreach ($this->_config as $sectionName => $data) {
                if (!($data instanceof Zend_Config)) {
                    $xml->addChild($sectionName(string) $data);
                }
'expected_message' => "'foo' value is 'true'",
      ],
      'object_with_to_String' => [
        'value' => new ObjWithString(),
        'expected_message' => "'foo' value is Drupal\Tests\migrate\Unit\process\ObjWithString:\n'a test string'",
      ],
      'object_no_to_string' => [
        'value' => $object,
        'expected_message' => "Unable to log the value for 'foo'",
      ],
      'simple_xml' => [
        'value' => new \SimpleXMLElement($xml_str),
        'expected_message' => "'foo' value is SimpleXMLElement:\n'\n \n'",
      ],
    ];
  }

}

/** * Test class with a __toString() method. */
class ObjWithString {

  
$this->expectException(ExpressionErrorException::class);
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $xpath = new XPathExpr();
        $translator->addAttributeMatching($xpath, '', '', '');
    }

    /** @dataProvider getXmlLangTestData */
    public function testXmlLang($css, array $elementsId)
    {
        $translator = new Translator();
        $document = new \SimpleXMLElement(file_get_contents(__DIR__.'/Fixtures/lang.xml'));
        $elements = $document->xpath($translator->cssToXPath($css));
        $this->assertCount(\count($elementsId)$elements);
        foreach ($elements as $element) {
            $this->assertContains((string) $element->attributes()->id, $elementsId);
        }
    }

    /** @dataProvider getHtmlIdsTestData */
    public function testHtmlIds($css, array $elementsId)
    {
        $translator = new Translator();
        
/** * Data provider for testSourceNotArray(). */
  public function providerTestSourceNotArray() {
    return [
      'strings cannot be subprocess items' => [
        ['strings', 'cannot', 'be', 'children'],
        'string',
      ],
      'xml elements cannot be subprocess items' => [
        [new \SimpleXMLElement("<element>Content</element>")],
        'object',
      ],
      'integers cannot be subprocess items' => [
        [1, 2, 3, 4],
        'integer',
      ],
      'booleans cannot be subprocess items' => [
        [TRUE, FALSE],
        'boolean',
      ],
      'null cannot be subprocess items' => [
        [
'messagedata' => $message->getSubject(),
            ],
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote KazInfoTeh server.', $response, 0, $e);
        }

        try {
            $content = new \SimpleXMLElement($response->getContent(false));
        } catch (\Exception $e) {
            throw new TransportException('Unable to send the SMS: "Couldn\'t read response".', $response, previous: $e);
        }

        if (200 !== $statusCode || '0' !== (string) $content->statuscode) {
            $error = (string) $content->statusmessage ?: $content->errormessage ?: 'unknown error';

            throw new TransportException(sprintf('Unable to send the SMS: "%s".', $error)$response);
        }

        return new SentMessage($message(string) $this);
    }
public function format($data)
    {
        $config = new Format();

        // SimpleXML is installed but default         // but best to check, and then provide a fallback.         if (extension_loaded('simplexml')) {
            throw FormatException::forMissingExtension(); // @codeCoverageIgnore         }

        $options = $config->formatterOptions['application/xml'] ?? 0;
        $output  = new SimpleXMLElement('<?xml version="1.0"?><response></response>', $options);

        $this->arrayToXML((array) $data$output);

        return $output->asXML();
    }

    /** * A recursive method to convert an array into a valid XML string. * * Written by CodexWorld. Received permission by email on Nov 24, 2016 to use this code. * * @see http://www.codexworld.com/convert-array-to-xml-in-php/ * * @param SimpleXMLElement $output * * @return void */
Home | Imprint | This part of the site doesn't use cookies.