You are here

public function SimpleXMLFIReader::init in Feed Import 8

Here you'll init your reader.

Overrides FeedImportReader::init

File

feed_import_base/src/SimpleXMLFIReader.php, line 19

Class

SimpleXMLFIReader
SimpleXML Reader class, good for small-medium XML files.

Namespace

Drupal\feed_import_base

Code

public function init() {

  // Set default required options.
  $this->options += array(
    'class' => 'Drupal\\feed_import_base\\SimpleXMLElement',
    'options' => array(
      LIBXML_NOCDATA,
    ),
    'raw' => '',
    'stream' => NULL,
  );
  $opts = 0;
  foreach ($this->options['options'] as $opt) {
    $opts |= $opt;
  }
  $this->items = FALSE;

  // Try to fetch from URL.
  if ($this->options['url']) {
    if ($ctx = $this
      ->getStreamContext($this->options['stream'])) {
      libxml_set_streams_context($ctx);
    }
    $this->items = simplexml_load_file($this->options['url'], $this->options['class'], $opts);
  }
  elseif ($this->options['raw'] = trim($this->options['raw'])) {
    $this->items = simplexml_load_string($this->options['raw'], $this->options['class'], $opts);
  }
  else {

    // No raw or url resource provided.
    return FALSE;
  }

  // Add X inclusions, using a simple hack for SimpleXMLElement
  if ($this->items instanceof SimpleXMLElement && $opts & LIBXML_XINCLUDE) {
    dom_import_simplexml($this->items)->ownerDocument
      ->xinclude();
  }
  if (!$this->items) {
    return FALSE;
  }

  // Not needed anymore.
  unset($this->options['raw'], $opts);

  // Check for namespace settings.
  if (!empty($this->options['namespaces'])) {
    if (!is_array($this->options['namespaces'])) {
      $this->options['namespaces'] = static::cleanLines($this->options['namespaces']);
    }
    $this->nsname = $this->nsuri = array();
    foreach ($this->options['namespaces'] as $key => &$ns) {
      $ns = explode('=', $ns, 2);
      if (count($ns) != 2 || empty($ns[0]) || empty($ns[1])) {
        unset($this->options['namespaces'][$key]);
        continue;
      }
      list($this->nsname[], $this->nsuri[]) = $ns;

      // Set namespace.
      $this->items
        ->registerXPathNamespace($ns[0], $ns[1]);
    }

    // Not needed anymore.
    unset($this->options['namespaces'], $ns);
    if ($this->nsname) {
      $this->nsfunc = array(
        NULL,
        'registerXPathNamespace',
      );
    }
  }
  else {
    $this->nsname = $this->nsuri = NULL;
  }
  if (!($this->items = $this->items
    ->xpath($this->options['parent']))) {
    return FALSE;
  }
  return TRUE;
}