简体   繁体   中英

php getimagesize with persian file name

I'm trying to write an Joomla plugin to add width and height tag to each <img> in HTML file. Some image file names are Persian, and getimagesize faces error.

The code is this:

   @$dom->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <img src="images\banners\س.jpg" style="max-width: 90%;" >
    </body>
    </html>
');

   $x = new DOMXPath($dom);

    foreach($x->query("//img") as $node)
    {   
        $imgtag = $node->getAttribute("src");
        
        $imgtag = pathinfo($imgtag);
        $imgtag = $imgtag['dirname'].'\\'.$imgtag['basename'];
        $imgtag = getimagesize($imgtag);
        
        $node->setAttribute("width",$imgtag[0]);
        $node->setAttribute("height",$imgtag[1]);
    }
    $newHtml = urldecode($dom->saveHtml($dom->documentElement));

And when Persian characters exist in file name, getimagesize shows:

Warning: getimagesize(images\\banners\\س.jpg): failed to open stream: No such file or directory in C:\\wamp64\\www\\plugin.php

How can I solve this?

Thanks to all, I couldn't reach to results on WAMP server (local server on Windows), but when I migrated to Linux server, finally this code worked properly.


        $html = $app->getBody();

        setlocale(LC_ALL, '');
        $dom = new DOMDocument();
        @$dom->loadHTML($html);

        $x = new DOMXPath($dom);

        foreach($x->query("//img") as $node)
        {   
                $imgtag = $node->getAttribute("src");
            if(strpos($imgtag,"data:image")===false)
            {

                $imgtag = getimagesize($imgtag);
                
                $node->setAttribute("width",$imgtag[0]);
                $node->setAttribute("height",$imgtag[1]);
            }
        }

        $bodytag = $x->query("//body");
        $node = $dom->createElement("script", ' /* java script which may be necessary on client */ '); 

        $bodytag[0]->appendChild($node);

        $html = '<!DOCTYPE html>'."\n" . $dom->saveHtml($dom->documentElement);

Some hints:

  1. the code, shouldn't touch base64 image sources, so I added an condition to the code.
  2. if some script (or whatever, div, p, ....) should be added to body tag, you can use appendChild method.
  3. <!DOCTYPE html> should be added to final DOM object output :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM