How to use "If then" nested into a string variable

I have been away from PHP for a little while and maybe I have forgotten the basics but here is something like I want to do to Build an XML file.

I am having trouble formatting the “IF” statement in the string so that it works inside of the string variable.

Maybe it is an easy fix and I have just been away too long?

$scannercapabilities='<scan:ScannerCapabilities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:scan="http://schemas.hp.com/imaging/escl/2011/05/03" xmlns:pwg="http://www.pwg.org/schemas/2010/12/sm" xsi:schemaLocation="http://schemas.hp.com/imaging/escl/2011/05/03 eSCL.xsd">
        <pwg:Version>2.0</pwg:Version>
	<pwg:MakeAndModel>'.$scannername.'</pwg:MakeAndModel>
        <pwg:SerialNumber>'.$serialnumber.'</pwg:SerialNumber>
        <scan:UUID>'.$uuid.'</scan:UUID>
        <scan:AdminURI>http://'.$hostname.'./airscan.php</scan:AdminURI>
	<scan:IconURI>http://'.$hostname.'/images/AirScanIcon2.png</scan:IconURI>
        <scan:Platen>
                <scan:PlatenInputCaps>
                        <scan:MinWidth>300</scan:MinWidth>
                        <scan:MaxWidth>2575</scan:MaxWidth>
                        <scan:MinHeight>300</scan:MinHeight>
                        <scan:MaxHeight>4783</scan:MaxHeight>
                        <scan:MaxScanRegions>0</scan:MaxScanRegions>
                        <scan:SettingProfiles>
                                <scan:SettingProfile>
                                        <scan:ColorModes>
                                           '.(if ($mode24bitcolor=="yes") echo "<scan:ColorMode>RGB24</scan:ColorMode>";).' 
<.....more xml>';

the problem is the bottom line with $mode24bitcolor variable . Seems no matter how I format it I get an error. the variables in the beginning are fine. php seems to trip up on the “If” statement

It should be possible to build this variable from other vartiables.

I have tried this with and without parenthesis and with and without “.” to concatenate

Using echo during an expression makes no sense; it’s a command to output something. You could use a ternary operator:

$scannercapabilities='...
<scan:ColorModes>' .
    ($mode24bitcolor == "yes" ? '<scan:ColorMode>RGB24</scan:ColorMode>' : '') .
    '<...more xml>';

Works beautifully , thanks so much. Is this something changed in newer PHP versions?

As near as I can make out, they’ve been available in every version of PHP since pretty early on. I can’t see them in the release notes at all, so at least PHP 3. They’re useful for simple circumstances like this but can get unwieldy quickly if you ask too much of them.

Sponsor our Newsletter | Privacy Policy | Terms of Service