PHP将外部文本转换为来自其他域的GET CURL的变量,如:https://somedomain.com/file.txt
此 file.txt 包含一些文字和变量,例如:
欢迎来到我们的$ STORENAME商店,$ CUSTOMERNAME
我们的商店位于某处的$ STOREADDRESS。
您会看到文本中包含一些变量。
当我在我的域中的PHP文件中获取文本时: https://example.com/emailer.php
此 emailer.php 文件为:
<?php
# Defining variables to use in the text we acquire:
$STORENAME = "candy";
$CUSTOMERNAME = "William";
$STOREADDRESS = "123 Store Street";
# Get the text from another domain:
$CURL = curl_init();
curl_setopt($CURL, CURLOPT_URL, "https://somedomain.com/file.txt");
curl_setopt($CURL, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($CURL);
echo "$result";
实际结果:
欢迎来到我们的$ STORENAME商店,$ CUSTOMERNAME
我们的商店位于某处的$ STOREADDRESS。
预期结果:
欢迎来到我们的糖果店威廉
我们的商店位于某商店街123号。
如何让PHP解析变量,而不是将它们视为文本?
不使用等功能,例如eval()或没有启用远程包含&#34; allow_url_include&#34;或没有正则表达式或没有爆炸打破文本和重新合并......
答案 0 :(得分:2)
您最好的选择是在这种情况下使用str_replace,如下所示:
<?php
$STORENAME = "candy";
$CUSTOMERNAME = "William";
$STOREADDRESS = "123 Store Street";
$result = 'Welcome to our $STORENAME store, $CUSTOMERNAME<br>
Our store is located at $STOREADDRESS in somewhere.';
$result = str_replace(
array('$STORENAME','$CUSTOMERNAME','$STOREADDRESS'),
array($STORENAME,$CUSTOMERNAME,$STOREADDRESS),
$result
);
echo $result;
答案 1 :(得分:0)
您可以将str_replace
与您定义的键/值对一起使用:
# Defining variables to use in the text we acquire:
$replacement_array = array(
'$STORENAME' => "candy",
'$CUSTOMERNAME' => "William",
'$STOREADDRESS' => "123 Store Street"
);
# Get the text from another domain:
// PUT YOUR CURL CODE HERE - FOR THIS EXAMPLE WE'LL JUST USE $message
$message = '
Welcome to our $STORENAME store, $CUSTOMERNAME
Our store is located at $STOREADDRESS in somewhere.
';
# Define your replacement array
echo str_replace(array_keys($replacement_array), $replacement_array, $message);