0

I am looking for a way to obtain a Python list and display it on my website using PHP.

I've checked out and tried many online help-requests so I was hoping someone would be able to explain to me what it is I am doing wrong.

My Python script scrapes a website and puts the result in a Python list.

What I am trying to achieve is the following:

  • I want to display (a part) of the list on my website.

I've tried to accomplish this with the following code:

PHP

<?php

  $outputArray = [];
  $returnStatus;

  exec('python ./scrapeWebsite.py', $outputArray, $returnStatus);
  var_dump($outputArray);
  echo $returnStatus;

?>

Python:

print(newsHeadlines) -> returning a list like this: ['item 1','item 2','item 3','item 4']

However, the array comes back as array(0) { } and the $returnStatus value is 1.

4
  • 1
    Easiest thing to do would probably be to just dump JSON to disk from your Python script, and read that file from PHP Commented Mar 14, 2018 at 19:27
  • The output of your exec call is a string, not an array. So store the result in a string, then use PHP to cut it and make it an array, if you must (hint, PHP explode). Commented Mar 14, 2018 at 19:33
  • How about going directly to python instead of trying to cobble PHP into the middle? Commented Mar 14, 2018 at 22:57
  • A better, no-file reply using JSON: stackoverflow.com/questions/46226655/… Commented Jun 30, 2019 at 8:29

1 Answer 1

0

Encoding the list with JSON and writing it to a file on the disk, and then reading the file in PHP and decoding JSON did the trick. To ensure the web-data is up-to-date I'm using exec(); to execute the python file.

If going full Python this is an option you could use.

To help others with a similar problem, this is the code I used:

Python:

myListJson = json.dumps(myList) #Encode our Python list into a JSON string

f = open("./fileName.txt", "w") #Open the file that we want to write to for write access

f.write(myListJson) #Write the JSON String to the file that we have currently open

f.close() #Close the file

PHP:

exec(python3 /path/to/file/script.py); //Will execute the python script, ensure the needed packages are installed on the **SERVER**.

$fileContents = file_get_contents("fileName.txt");

$decodedJson = json_decode($fileContents); //This will now contain your Array like any other PHP Array.

Thanks for the help!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.