Tarik
Tarik

Reputation: 4546

Get some text with CURL and parse only the variables inside with PHP

PHP is getting external text into a variable with GET CURL from another domain like: https://somedomain.com/file.txt

This file.txt contains some text and variables inside like:

Welcome to our $STORENAME store, $CUSTOMERNAME

Our store is located at $STOREADDRESS in somewhere.

You see the text contains some variables inside.

When I get the text in the PHP file in my domain like: https://example.com/emailer.php

This emailer.php file is:

<?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";

Actual Result:

Welcome to our $STORENAME store, $CUSTOMERNAME

Our store is located at $STOREADDRESS in somewhere.

Expected Result:

Welcome to our candy store, William

Our store is located at 123 Store Street in somewhere.

How to get PHP to parse the variables, not treat them like text?

And without using functions like eval() or without enabling remote include with "allow_url_include" or without regex or without explode to break text and re-merge...

Upvotes: 0

Views: 187

Answers (2)

Mike S
Mike S

Reputation: 1646

You can use str_replace with your defined key/value pairs:

# 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);

Example: https://eval.in/861140

Upvotes: 0

Brian Gottier
Brian Gottier

Reputation: 4582

Your best option is to use str_replace in this situation, like this:

<?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;

Upvotes: 2

Related Questions