Home > Software engineering >  How to fix Uncaught TypeError: htmlspecialchars() expects parameter 1 to be string?
How to fix Uncaught TypeError: htmlspecialchars() expects parameter 1 to be string?

Time:12-08

I am unsure how to fix the following error in my Magento2 sitemap module: Uncaught TypeError: htmlspecialchars() expects parameter 1 to be string, null given in /var/www/html/app/code/SEO/XmlSitemap/Model/Writer.php:388

 protected function getImageXml(DataObject $images): string
    {
        $xml = '';
        foreach ($images->getCollection() as $image) {

            $this->imageCount  ;
            $preparedImageUrl     = htmlspecialchars($image->getUrl());
            $preparedThumbnailUrl = htmlspecialchars($images->getThumbnail());
            $preparedTitle        = htmlspecialchars($images->getTitle());
            $preparedCaption      = $image->getCaption() ? htmlspecialchars($image->getCaption()) : '';

            $xmlImage = $this->getWrappedString($preparedImageUrl, 'image:loc');
            $xmlImage .= $this->getWrappedString($preparedTitle, 'image:title');
            if ($preparedCaption) {
                $xmlImage .= $this->getWrappedString($preparedCaption, 'image:caption');
            }

            $xml .= $this->getWrappedString($xmlImage, 'image:image');
        }

Line 388 is the following line:

$preparedTitle        = htmlspecialchars($images->getTitle());

The generation of the products sitemap.xml file, which is what this module is intended to do, returns a 500 error. How can I fix this?

CodePudding user response:

The $images->getTitle() method does not return a string. Are you sure you need to call this on the $images and not the $image variable? Even then you might want to be explicit:

$values = [
  'filled string' => 'string', 
  'empty string' => '', 
  'null value' => NULL, 
  'false value' => false, 
  'falsy value' => 0
];

foreach ($values as $label => $value) {
  echo "\n", $label, "\n"; 
  var_dump(
   [
     // original value
     $value, 
     // explicit string cast
     (string)$value, 
     // fallback if null or undefined
     $value ?? 'default', 
     // fallback if falsy
     $value ?: 'default'
   ]
  );
}
filled string
array(4) {
  [0]=>
  string(6) "string"
  [1]=>
  string(6) "string"
  [2]=>
  string(6) "string"
  [3]=>
  string(6) "string"
}

empty string
array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(7) "default"
}

null value
array(4) {
  [0]=>
  NULL
  [1]=>
  string(0) ""
  [2]=>
  string(7) "default"
  [3]=>
  string(7) "default"
}

false value
array(4) {
  [0]=>
  bool(false)
  [1]=>
  string(0) ""
  [2]=>
  bool(false)
  [3]=>
  string(7) "default"
}

falsy value
array(4) {
  [0]=>
  int(0)
  [1]=>
  string(1) "0"
  [2]=>
  int(0)
  [3]=>
  string(7) "default"
}
  • Related