Foreach循环问题(仅最后一个变量)

发布于 2024-10-01 06:57:03 字数 11728 浏览 2 评论 0原文

嘿伙计们,我有一点问题。我从 textarea 获取值作为数组,然后执行 foreach 循环,结果变得混乱,我有 2 个与 var 一起使用的函数,但只有一个可以正常工作,另一个只适用于数组的最后一个对象。 (我不是一个 php 专家,所以代码可能看起来很混乱)

<form action="example.php" method="post">
  <textarea name="tran" id="tran" rows="25" cols="20"></textarea>

   <input name="submit" type="submit" value="Submit">
</form>



 <?php
function translate($line) {
   $url = "http://m.translate.ru/translator/result/?text=$line&dirCode=gr";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.63 (Windows NT 5.1; U; ru) Presto/2.1.1");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $html = curl_exec($ch);
   curl_close($ch);
   preg_match('/<div class=\"tres\">(.*)<\/div><div class=\"tinfo\">/', $html, $translate);
   $blabla = strip_tags($translate[0]);
   return $blabla;

}
if(isset($_POST['submit'])) {
require("GTranslate.php");


$text = trim($_POST['tran']);
$textAr = explode("\n", $text);

$fp = fopen('data.txt', 'a+');
foreach ($textAr as $line) {
 try{
       $gt = new Gtranslate;
    $transl = $gt->german_to_english($line);
    $more_precise = translate($line);

fwrite($fp, $line);
fwrite($fp, "|");
fwrite($fp, $transl);
fwrite($fp, "|");
fwrite($fp, $more_precise);
fwrite($fp, "\n");


} catch (GTranslateException $ge)
 {
       echo $ge->getMessage();
 }
}
fclose($fp);
}
?>

这是 Gtranslate.php(从 google 代码得到的):

<?php

/**
* GTranslate - A class to comunicate with Google Translate(TM) Service
*               Google Translate(TM) API Wrapper
*               More info about Google(TM) service can be found on http://code.google.com/apis/ajaxlanguage/documentation/reference.html
*       This code has o affiliation with Google (TM) , its a PHP Library that allows to comunicate with public a API
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* @author Jose da Silva <[email protected]>
* @since 2009/11/18
* @version 0.7.4
* @licence LGPL v3
*
* <code>
*

     <?
    * require_once("GTranslate.php");
    * try{
    *   $gt = new Gtranslate;
    *   echo $gt->english_to_german("hello world");
    * } catch (GTranslateException $ge)
    * {
    *   echo $ge->getMessage();
    * }
    * ?>
    * </code>
    */


    /**
    * Exception class for GTranslated Exceptions
    */

    class GTranslateException extends Exception
    {
        public function __construct($string) {
            parent::__construct($string, 0);
        }

        public function __toString() {
            return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
        }
    }

    class GTranslate
    {
        /**
        * Google Translate(TM) Api endpoint
        * @access private
        * @var String 
        */
        private $url = "http://ajax.googleapis.com/ajax/services/language/translate";

            /**
            * Google Translate (TM) Api Version
            * @access private
            * @var String 
            */  
        private $api_version = "1.0";

            /**
            * Comunication Transport Method
        * Available: http / curl
            * @access private
            * @var String 
            */
        private $request_type = "http";

            /**
            * Path to available languages file
            * @access private
            * @var String 
            */
        private $available_languages_file   = "languages.ini";

            /**
            * Holder to the parse of the ini file
            * @access private
            * @var Array
            */
        private $available_languages = array();

        /**
        * Google Translate api key
        * @access private 
        * @var string
        */
        private $api_key = null;

        /**
        * Google request User IP
        * @access private
        * @var string   
        */
        private $user_ip = null;

            /**
            * Constructor sets up {@link $available_languages}
            */
        public function __construct()
        {
            $this->available_languages = parse_ini_file("languages.ini");
        }

            /**
            * URL Formater to use on request
            * @access private
            * @param array $lang_pair
        * @param array $string
        * "returns String $url
            */

        private function urlFormat($lang_pair,$string)
        {
            $parameters = array(
                "v" => $this->api_version,
                "q" => $string,
                "langpair"=> implode("|",$lang_pair)
            );

            if(!empty($this->api_key))
            {
                $parameters["key"] = $this->api_key;
            }

            if( empty($this->user_ip) ) 
            {
                if( !empty($_SERVER["REMOTE_ADDR"]) ) 
                {
                    $parameters["userip"]   =   $_SERVER["REMOTE_ADDR"];
                }
            } else 
            {
                $parameters["userip"]   =   $this->user_ip;
            }

            $url  = "";

            foreach($parameters as $k=>$p)
            {
                $url    .=  $k."=".urlencode($p)."&";
            }
            return $url;
        }

        /**
        * Define the request type
        * @access public
        * @param string $request_type
        * return boolean
        */
        public function setRequestType($request_type = 'http') {
            if (!empty($request_type)) {
                    $this->request_type = $request_type;
                return true;
            }
            return false;
        }

        /**
        * Define the Google Translate Api Key
        * @access public
        * @param string $api_key
        * return boolean
        */
        public function setApiKey($api_key) {
            if (!empty($api_key)) {
                    $this->api_key = $api_key;
                return true;
            }
            return false;
        }

        /**
        * Define the User Ip for the query
        * @access public
        * @param string $ip
        * return boolean
        */
        public function setUserIp($ip) {
            if (!empty($ip)) {
                    $this->user_ip = $ip;
                return true;
            }
            return false;
        }

            /**
            * Query the Google(TM) endpoint 
            * @access private
            * @param array $lang_pair
            * @param array $string
            * returns String $response
            */

        public function query($lang_pair,$string)
        {
            $query_url = $this->urlFormat($lang_pair,$string);
            $response = $this->{"request".ucwords($this->request_type)}($query_url);
            return $response;
        }

            /**
            * Query Wrapper for Http Transport 
            * @access private
            * @param String $url
            * returns String $response
            */

        private function requestHttp($url)
        {
            return GTranslate::evalResponse(json_decode(file_get_contents($this->url."?".$url)));
        }

            /**     
            * Query Wrapper for Curl Transport 
            * @access private
            * @param String $url
            * returns String $response
            */

        private function requestCurl($url)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
            $body = curl_exec($ch);
            curl_close($ch);
            return GTranslate::evalResponse(json_decode($body));
        }

            /**     
            * Response Evaluator, validates the response
        * Throws an exception on error 
            * @access private
            * @param String $json_response
            * returns String $response
            */

        private function evalResponse($json_response)
        {
            switch($json_response->responseStatus)
            {
                case 200:
                    return $json_response->responseData->translatedText;
                    break;
                default:
                    throw new GTranslateException("Unable to perform Translation:".$json_response->responseDetails);
                break;
            }
        }


            /**     
            * Validates if the language pair is valid
            * Throws an exception on error 
            * @access private
            * @param Array $languages
            * returns Array $response Array with formated languages pair
            */

        private function isValidLanguage($languages)
        {
            $language_list  = $this->available_languages;

            $languages      =   array_map( "strtolower", $languages );
            $language_list_v    =   array_map( "strtolower", array_values($language_list) );
            $language_list_k    =   array_map( "strtolower", array_keys($language_list) );
            $valid_languages    =   false;
            if( TRUE == in_array($languages[0],$language_list_v) AND TRUE == in_array($languages[1],$language_list_v) )
            {
                $valid_languages    =   true;   
            }

            if( FALSE === $valid_languages AND TRUE == in_array($languages[0],$language_list_k) AND TRUE == in_array($languages[1],$language_list_k) )
            {
                $languages  =   array($language_list[strtoupper($languages[0])],$language_list[strtoupper($languages[1])]);
                $valid_languages        =       true;
            }

            if( FALSE === $valid_languages )
            {
                throw new GTranslateException("Unsupported languages (".$languages[0].",".$languages[1].")");
            }

            return $languages;
        }

            /**     
            * Magic method to understande translation comman
        * Evaluates methods like language_to_language
            * @access public
        * @param String $name
            * @param Array $args
            * returns String $response Translated Text
            */


        public function __call($name,$args)
        {
            $languages_list     =   explode("_to_",strtolower($name));
            $languages = $this->isValidLanguage($languages_list);

            $string     =   $args[0];
            return $this->query($languages,$string);
        }
    }

    ?>

Gtranslate.php 没有任何问题,它工作正常。

再次关于我的问题,我从文本文件中的单词进行 foreach 循环,每个单词都翻译成英语,然后我得到另一个数据(但对我来说更精确),第一部分工作正常,第二部分仅适用于数组的最后一个字。

我希望你明白我的问题是什么。

预先感谢您的答复。

Hey guys, I have a bit of a problem. I get values from textarea as an array, then I do a foreach loop and there it gets messy, I have 2 functions that work with the vars, but only one them works normally, the other one only works on the last objest of an array.
(I'm not much of a php specialist so the code might look messy)

<form action="example.php" method="post">
  <textarea name="tran" id="tran" rows="25" cols="20"></textarea>

   <input name="submit" type="submit" value="Submit">
</form>



 <?php
function translate($line) {
   $url = "http://m.translate.ru/translator/result/?text=$line&dirCode=gr";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.63 (Windows NT 5.1; U; ru) Presto/2.1.1");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $html = curl_exec($ch);
   curl_close($ch);
   preg_match('/<div class=\"tres\">(.*)<\/div><div class=\"tinfo\">/', $html, $translate);
   $blabla = strip_tags($translate[0]);
   return $blabla;

}
if(isset($_POST['submit'])) {
require("GTranslate.php");


$text = trim($_POST['tran']);
$textAr = explode("\n", $text);

$fp = fopen('data.txt', 'a+');
foreach ($textAr as $line) {
 try{
       $gt = new Gtranslate;
    $transl = $gt->german_to_english($line);
    $more_precise = translate($line);

fwrite($fp, $line);
fwrite($fp, "|");
fwrite($fp, $transl);
fwrite($fp, "|");
fwrite($fp, $more_precise);
fwrite($fp, "\n");


} catch (GTranslateException $ge)
 {
       echo $ge->getMessage();
 }
}
fclose($fp);
}
?>

Here's the Gtranslate.php (got it from google code):

<?php

/**
* GTranslate - A class to comunicate with Google Translate(TM) Service
*               Google Translate(TM) API Wrapper
*               More info about Google(TM) service can be found on http://code.google.com/apis/ajaxlanguage/documentation/reference.html
*       This code has o affiliation with Google (TM) , its a PHP Library that allows to comunicate with public a API
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* @author Jose da Silva <[email protected]>
* @since 2009/11/18
* @version 0.7.4
* @licence LGPL v3
*
* <code>
*

     <?
    * require_once("GTranslate.php");
    * try{
    *   $gt = new Gtranslate;
    *   echo $gt->english_to_german("hello world");
    * } catch (GTranslateException $ge)
    * {
    *   echo $ge->getMessage();
    * }
    * ?>
    * </code>
    */


    /**
    * Exception class for GTranslated Exceptions
    */

    class GTranslateException extends Exception
    {
        public function __construct($string) {
            parent::__construct($string, 0);
        }

        public function __toString() {
            return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
        }
    }

    class GTranslate
    {
        /**
        * Google Translate(TM) Api endpoint
        * @access private
        * @var String 
        */
        private $url = "http://ajax.googleapis.com/ajax/services/language/translate";

            /**
            * Google Translate (TM) Api Version
            * @access private
            * @var String 
            */  
        private $api_version = "1.0";

            /**
            * Comunication Transport Method
        * Available: http / curl
            * @access private
            * @var String 
            */
        private $request_type = "http";

            /**
            * Path to available languages file
            * @access private
            * @var String 
            */
        private $available_languages_file   = "languages.ini";

            /**
            * Holder to the parse of the ini file
            * @access private
            * @var Array
            */
        private $available_languages = array();

        /**
        * Google Translate api key
        * @access private 
        * @var string
        */
        private $api_key = null;

        /**
        * Google request User IP
        * @access private
        * @var string   
        */
        private $user_ip = null;

            /**
            * Constructor sets up {@link $available_languages}
            */
        public function __construct()
        {
            $this->available_languages = parse_ini_file("languages.ini");
        }

            /**
            * URL Formater to use on request
            * @access private
            * @param array $lang_pair
        * @param array $string
        * "returns String $url
            */

        private function urlFormat($lang_pair,$string)
        {
            $parameters = array(
                "v" => $this->api_version,
                "q" => $string,
                "langpair"=> implode("|",$lang_pair)
            );

            if(!empty($this->api_key))
            {
                $parameters["key"] = $this->api_key;
            }

            if( empty($this->user_ip) ) 
            {
                if( !empty($_SERVER["REMOTE_ADDR"]) ) 
                {
                    $parameters["userip"]   =   $_SERVER["REMOTE_ADDR"];
                }
            } else 
            {
                $parameters["userip"]   =   $this->user_ip;
            }

            $url  = "";

            foreach($parameters as $k=>$p)
            {
                $url    .=  $k."=".urlencode($p)."&";
            }
            return $url;
        }

        /**
        * Define the request type
        * @access public
        * @param string $request_type
        * return boolean
        */
        public function setRequestType($request_type = 'http') {
            if (!empty($request_type)) {
                    $this->request_type = $request_type;
                return true;
            }
            return false;
        }

        /**
        * Define the Google Translate Api Key
        * @access public
        * @param string $api_key
        * return boolean
        */
        public function setApiKey($api_key) {
            if (!empty($api_key)) {
                    $this->api_key = $api_key;
                return true;
            }
            return false;
        }

        /**
        * Define the User Ip for the query
        * @access public
        * @param string $ip
        * return boolean
        */
        public function setUserIp($ip) {
            if (!empty($ip)) {
                    $this->user_ip = $ip;
                return true;
            }
            return false;
        }

            /**
            * Query the Google(TM) endpoint 
            * @access private
            * @param array $lang_pair
            * @param array $string
            * returns String $response
            */

        public function query($lang_pair,$string)
        {
            $query_url = $this->urlFormat($lang_pair,$string);
            $response = $this->{"request".ucwords($this->request_type)}($query_url);
            return $response;
        }

            /**
            * Query Wrapper for Http Transport 
            * @access private
            * @param String $url
            * returns String $response
            */

        private function requestHttp($url)
        {
            return GTranslate::evalResponse(json_decode(file_get_contents($this->url."?".$url)));
        }

            /**     
            * Query Wrapper for Curl Transport 
            * @access private
            * @param String $url
            * returns String $response
            */

        private function requestCurl($url)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
            $body = curl_exec($ch);
            curl_close($ch);
            return GTranslate::evalResponse(json_decode($body));
        }

            /**     
            * Response Evaluator, validates the response
        * Throws an exception on error 
            * @access private
            * @param String $json_response
            * returns String $response
            */

        private function evalResponse($json_response)
        {
            switch($json_response->responseStatus)
            {
                case 200:
                    return $json_response->responseData->translatedText;
                    break;
                default:
                    throw new GTranslateException("Unable to perform Translation:".$json_response->responseDetails);
                break;
            }
        }


            /**     
            * Validates if the language pair is valid
            * Throws an exception on error 
            * @access private
            * @param Array $languages
            * returns Array $response Array with formated languages pair
            */

        private function isValidLanguage($languages)
        {
            $language_list  = $this->available_languages;

            $languages      =   array_map( "strtolower", $languages );
            $language_list_v    =   array_map( "strtolower", array_values($language_list) );
            $language_list_k    =   array_map( "strtolower", array_keys($language_list) );
            $valid_languages    =   false;
            if( TRUE == in_array($languages[0],$language_list_v) AND TRUE == in_array($languages[1],$language_list_v) )
            {
                $valid_languages    =   true;   
            }

            if( FALSE === $valid_languages AND TRUE == in_array($languages[0],$language_list_k) AND TRUE == in_array($languages[1],$language_list_k) )
            {
                $languages  =   array($language_list[strtoupper($languages[0])],$language_list[strtoupper($languages[1])]);
                $valid_languages        =       true;
            }

            if( FALSE === $valid_languages )
            {
                throw new GTranslateException("Unsupported languages (".$languages[0].",".$languages[1].")");
            }

            return $languages;
        }

            /**     
            * Magic method to understande translation comman
        * Evaluates methods like language_to_language
            * @access public
        * @param String $name
            * @param Array $args
            * returns String $response Translated Text
            */


        public function __call($name,$args)
        {
            $languages_list     =   explode("_to_",strtolower($name));
            $languages = $this->isValidLanguage($languages_list);

            $string     =   $args[0];
            return $this->query($languages,$string);
        }
    }

    ?>

Gtranslate.php doesn't have any problems it works ok.

So again about my problem, I do a foreach loop from words that are in the textfile, each gets translated into english and then I get another data (but more precise for me) the first part works fine, the second part only works on the last word of the array.

I hope you understand what my problem is.

Thank you in advance for your answers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

星星的轨迹 2024-10-08 06:57:03

尝试将修剪移到循环数据之后,否则每行仍然可能有前后空格。

<form action="example.php" method="post">
  <textarea name="tran" id="tran" rows="25" cols="20"></textarea>

   <input name="submit" type="submit" value="Submit">
</form>



 <?php
function translate($line) {
   $url = "http://m.translate.ru/translator/result/?text=$line&dirCode=gr";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.63 (Windows NT 5.1; U; ru) Presto/2.1.1");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $html = curl_exec($ch);
   curl_close($ch);
   preg_match('/<div class=\"tres\">(.*)<\/div><div class=\"tinfo\">/', $html, $translate);
   $blabla = strip_tags($translate[0]);
   return $blabla;

}
if(isset($_POST['submit'])) {
require("GTranslate.php");



$textAr = explode("\n", $_POST['tran']);

$fp = fopen('data.txt', 'a+');
foreach ($textAr as $line) {
 try{

       $gt = new Gtranslate;
    $transl = $gt->german_to_english(trim($line));
    $more_precise = translate($line);

fwrite($fp, $line."|".$transl."|".$more_precise."\n");


} catch (GTranslateException $ge)
 {
       echo $ge->getMessage();
 }
}
fclose($fp);
}
?>

try moving your trim to after you're looping through the data, else each line could still have whitespace front and back.

<form action="example.php" method="post">
  <textarea name="tran" id="tran" rows="25" cols="20"></textarea>

   <input name="submit" type="submit" value="Submit">
</form>



 <?php
function translate($line) {
   $url = "http://m.translate.ru/translator/result/?text=$line&dirCode=gr";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_USERAGENT, "Opera/9.63 (Windows NT 5.1; U; ru) Presto/2.1.1");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $html = curl_exec($ch);
   curl_close($ch);
   preg_match('/<div class=\"tres\">(.*)<\/div><div class=\"tinfo\">/', $html, $translate);
   $blabla = strip_tags($translate[0]);
   return $blabla;

}
if(isset($_POST['submit'])) {
require("GTranslate.php");



$textAr = explode("\n", $_POST['tran']);

$fp = fopen('data.txt', 'a+');
foreach ($textAr as $line) {
 try{

       $gt = new Gtranslate;
    $transl = $gt->german_to_english(trim($line));
    $more_precise = translate($line);

fwrite($fp, $line."|".$transl."|".$more_precise."\n");


} catch (GTranslateException $ge)
 {
       echo $ge->getMessage();
 }
}
fclose($fp);
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文