简体   繁体   中英

Quote marks appearing in echo sentence

I'm building a webpage using PHP. I have a table with multiple buttons. I'm building the buttons in a for loop using the following code:

        echo "<tr><td><input type='button' value='".$row['Descripcion']."'";
        echo "onclick=EliminarHashTag('".$row['ID']."','";
        echo $row['Descripcion'];
        echo "','Norma','".$Codigo."','".$Organizacion."')> </td></tr>";   

It all works fine as long as my variables are strings made of single words.. For example, if it's $row['Descripcion']="manometros" , (string without whitespace) the echo outputs the following:

<input type="button" value="Manometros" onclick="EliminarHashTag('14','Manometros','norma','k-300','pdvsa')="">

but if my variable is made of a string with whitespace $row['Descripcion']="Criterios Generales" , the echo outputs quote marks in the whitespace, messing up the javascript function call syntax and hence making the code not work (Criterios" Generales).

<input type="button" value="Criterios Generales" onclick="EliminarHashTag('14','Criterios" generales','norma','k-300','pdvsa')="">

I read the echo documentation at php.net, but I saw no mention of this issue. Am I doing something wrong?

If you do not quote an attribute, the attributes value ends at the first whitespace or the end of the tag.

Add quotes around the onclick...

echo " onclick=\"EliminarHashTag('".$row['ID']."','";
      ^^       ^^       

and

echo "','Norma','".$Codigo."','".$Organizacion."')\"> </td></tr>"; 
                                                  ^^

Now if any of the values have double quotes they need to be escaped as html entitles. Or you would need to swap the single for double.

Your HTML is invalid, debugging tools like firebug and chrome developer tools try to correct it to display a proper domtree.

You're not only missing the closing quote on your onclick attribute but also break the encapsulation by using the same type of quotes inside your onclick function arguments:

 echo '<tr><td><input type="button" value="'.$row['Descripcion'].'"';
 echo 'onclick="EliminarHashTag(\''.$row['ID'].'\',\'';
 echo $row['Descripcion'];
 echo '\',\'Norma\',\''.$Codigo.'\',\''.$Organizacion.'\')"> </td></tr>';   

Try escaping the quotes with back slashes:

    echo "onclick=EliminarHashTag('".$row['ID']."',\"";
    echo $row['Descripcion'];
    echo "\",'Norma','".$Codigo."','".$Organizacion."')> </td></tr>";

I changed the ' before and after your variable to \\" .

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