You are here

public function SearchApiSolrDocument::toXml in Search API Solr 7

Create an XML fragment from this document.

This string can then be used inside a Solr add call.

Return value

string An XML formatted string for this document.

File

includes/document.inc, line 449

Class

SearchApiSolrDocument
Holds Key / Value pairs that represent a Solr Document along with any associated boost values. Field values can be accessed by direct dereferencing such as:

Code

public function toXml() {
  $xml = '<doc';
  if ($this->documentBoost !== FALSE) {
    $xml .= ' boost="' . $this->documentBoost . '"';
  }
  $xml .= '>';
  foreach ($this->fields as $key => $values) {
    $fieldBoost = $this
      ->getFieldBoost($key);
    $fieldUpdate = $this
      ->getFieldUpdate($key);
    $key = htmlspecialchars($key, ENT_COMPAT, 'UTF-8');
    if (!is_array($values)) {
      $values = array(
        $values,
      );
    }
    foreach ($values as $value) {
      $xml .= '<field name="' . $key . '"';
      if ($fieldBoost !== FALSE) {
        $xml .= ' boost="' . $fieldBoost . '"';

        // Only set the boost for the first field in the set.
        $fieldBoost = FALSE;
      }
      if ($fieldUpdate !== FALSE) {
        $xml .= ' update="' . $fieldUpdate . '"';
      }
      $xml .= '>' . htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8') . '</field>';
    }
  }

  // If nested objects have been added, include them in the XML to be indexed.
  foreach ($this->nestedObjects as $object) {

    // Skip any documents that aren't of the correct type.
    if (!$object instanceof SearchApiSolrDocument) {
      $vars['@type'] = is_object($object) ? get_class($object) : gettype($object);
      watchdog('search_api_solr', 'Attempt to add an invalid nested Solr document of type @type.', $vars, WATCHDOG_ERROR);
      continue;
    }

    // Generate the markup for each nested document.
    $xml .= $object
      ->toXml();
  }
  $xml .= '</doc>';

  // Remove any control characters to avoid Solr XML parser exception.
  return self::stripCtrlChars($xml);
}