In your python script do something like

import json
#some code here
jsonStr = json.dumps(myListFromGooglePlaces)
#whatever you do to get it to php

and then as mentioned in my comment above

$arr = json_decode($json, true);

I hope that works for you.

Answer from Domenik Reitzner on Stack Overflow
Top answer
1 of 16
1825

Just typecast it

$array = (array) $yourObject;

From Arrays:

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Example: Simple Object

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

array(2) {
  'foo' => int(1)
  'bar' => int(2)
}

Example: Complex Object

class Foo
{
    private $foo;
    protected $bar;
    public $baz;

    public function __construct()
    {
        $this->foo = 1;
        $this->bar = 2;
        $this->baz = new StdClass;
    }
}

var_dump( (array) new Foo );

Output (with \0s edited in for clarity):

array(3) {
  '\0Foo\0foo' => int(1)
  '\0*\0bar' => int(2)
  'baz' => class stdClass#2 (0) {}
}

Output with var_export instead of var_dump:

array (
  '' . "\0" . 'Foo' . "\0" . 'foo' => 1,
  '' . "\0" . '*' . "\0" . 'bar' => 2,
  'baz' =>
  stdClass::__set_state(array(
  )),
)

To know more about php built-in class stdclass. You can read this documentation

Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.

Also see this in-depth blog post:

  • Fast PHP Object to Array conversion
2 of 16
540

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($nested_object), true);
Discussions

To understand: From PHP Array to Python? - Stack Overflow
This is Common task In PHP and other programming languages.I moved from PHP developer. I want to make sure with this collections. Anyone have who good in python please help me to understand clearly . More on stackoverflow.com
🌐 stackoverflow.com
How to convert an array to object in PHP? - Stack Overflow
How can I convert an array like this to an object? [128] => Array ( [status] => "Figure A. Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."... More on stackoverflow.com
🌐 stackoverflow.com
Converting python dictionary into something php can use? Associative Array?

I would suggest using JSON, the whole point of it is to make communicating between computers/devices/software/languages easier...so, take the help :D

I dunno how to do it on Py end, but with PHP you would just use json_decode (second param is for result of json_decode to be assoc. array)

 foreach (json_decode($output, true) as $item) {
More on reddit.com
🌐 r/PHPhelp
5
5
February 20, 2017
PHP Recursively Convert Object to Array - Stack Overflow
I am trying to recursively convert a php object to an array. The function I wrote is this: public function object_to_array($obj) { $array = (array) $obj; foreach ($array as $attribute) { ... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How can I convert an array back into an object in PHP?
You can easily convert an array back to an object in PHP by casting the array to an object using typecasting, like this: $object = (object) $array;. This method is particularly useful when you need to work with data in an object-oriented way, such as when manipulating data within classes and methods. For nested arrays, JSON encoding/decoding is also an option to achieve the reverse conversion.
🌐
upgrad.com
upgrad.com › home › blog › software development › how to convert object to array in php? techniques and examples
How to Convert Object to Array in PHP – Quick & Simple Methods
Can I use JSON encoding/decoding for all objects when learning how to convert object to array in PHP?
While JSON encoding/decoding is versatile, it isn't suitable for all objects when learning how to convert object to array in PHP. For instance, it doesn’t work well with resources (like file handles or database connections) or objects with non-UTF8 characters. Always check the compatibility of your object before using JSON methods, especially when dealing with special data types or large resources.
🌐
upgrad.com
upgrad.com › home › blog › software development › how to convert object to array in php? techniques and examples
How to Convert Object to Array in PHP – Quick & Simple Methods
Why does get_object_vars() fail with non-public properties when learning how to convert object to array in PHP?
get_object_vars() only works with public properties, so when learning how to convert object to array in PHP with private or protected properties, it won’t include those properties. If you need to include non-public properties in the array, you can either use Reflection to access them or create getter methods in the class to expose those properties before conversion.
🌐
upgrad.com
upgrad.com › home › blog › software development › how to convert object to array in php? techniques and examples
How to Convert Object to Array in PHP – Quick & Simple Methods
Top answer
1 of 2
5

Update: A Completely different approach

There is a difficulty with the PHP script JSON-encoding a structure to produce a JSON string and then passing it as a command line argument since the string needs to be placed in double quotes because there can be embedded spaces in the encoded string. But the string itself can contain double quotes as start of string characters and within such a string. Confused? Who wouldn't be?

There is no problem however with writing such a string to a file and having the Python program read it in and decode it. But we don't want to have to deal with temporary files. So the solution is to pipe the data to the Python program where it can then be read in as stdin

Let's assume your array looks like:

$arr =
[
    [
        "FileName" => "\"\\  \nRon's20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

Note that I have modified your example slightly so that the first FileName field contains a " character, a ' character, an escape sequence \n representing the newline character and finally some spaces. Although your example does not contain these characters or some other escape sequence, I would like to be able to handle such a condition should it arise. This solution should work with such input.

PHP File

<?php
$arr =
[
    [
        "FileName" => "\"\\  \nRon's20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

// Encode string as JSON:
$json = json_encode($arr);

// Pipe the JSON string to the Python process's stdin and
// read the result from its stdout:
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w")   // stdout is a pipe that the child will write to
);
$options = array('bypass_shell' => True); // Only has effect on Windows
//$process = proc_open("python3 test.py", $descriptorspec, $pipes, null, null, $options);
// For your actual environment:
$process = proc_open("D:/Anaconda/python.exe D:/xampp/htdocs/Klasifikasi_KNN/admin/test.py", $descriptorspec, $pipes, null, null, $options);

// Pipe the input for the Python program and close the pipe:
fwrite($pipes[0], $json);
fclose($pipes[0]);

// Read the result from the Python program and close its pipe
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);

# Now that we have closed the pipes, we can close the process:
$return_code = proc_close($process);

echo "Result from stdin:\n$result\n";

test.py

import json
import sys

DEBUG = True # for debugging purposes

if DEBUG:
    import os

    for k, v in sorted(os.environ.items()):
        print(k, '->', v, file=sys.stderr)
else:
    import numpy as np
    import pandas as pd

# Load from stdin:
arr = json.load(sys.stdin)
# print each dictionary of the array:
for d in arr:
    print(d)

Prints:

{'FileName': '"\\  \nRon\'s20221227_202035.jpg', 'Model': '27_202035.jpg', 'Longitude': 106.90425, 'Latitude': 106.90425}
{'FileName': '20221227_202157.jpg', 'Model': 'SM-A528B', 'Longitude': 106.9042428, 'Latitude': -6.1676580997222}
2 of 2
3

You just need to enclose in single quotes the argument to python:

shell_exec("python3 test.py '$json'");

Example

file.php

$data =
[
    [
        "FileName" => "20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

$json = json_encode($data);

// note: arg '$json' is single-quoted
echo shell_exec("python3 test.py '$json'");

test.py

import sys
import json
from pandas import json_normalize

data = sys.argv[1]

dict = json.loads(data)
df2 = json_normalize(dict) 

print(df2)

Output

              FileName     Model   Longitude  Latitude
0  20221227_202035.jpg  SM-A528B  106.904251 -6.167665
1  20221227_202157.jpg  SM-A528B  106.904243 -6.167658

See: Escaping double qoutes when sending JSON as argument in python program

🌐
Upgrad
upgrad.com › home › blog › software development › how to convert object to array in php? techniques and examples
How to Convert Object to Array in PHP – Quick & Simple Methods
September 10, 2025 - This will help you learn how to convert an object to an array in PHP and ensure you're well-prepared for real-life scenarios. For further growth in PHP, upGrad’s courses in web development and backend programming can help you learn complex data structures and concurrency. In addition to the courses mentioned above, here are some more free courses that can help you advance your skills: Learn Basic Python Programming ·
🌐
EDUCBA
educba.com › home › software development › software development tutorials › php tutorial › php object to array
PHP object to array | How to Convert object to array in PHP with example?
April 18, 2023 - Typecasting is a technique in which one data type variable into the another data type. It is considered as an explicit data type conversion. It can translate a PHP object to an array with the help of typecasting rules in PHP.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
PyPI
pypi.org › project › phpserialize
phpserialize · PyPI
a port of the serialize and unserialize functions of php to python.
Find elsewhere
Top answer
1 of 4
30

All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.

Example 1

PHP

$php = array(1,2,3,4,5,6,7,8,9,10);
for (i < 10 ; $i ++)
echo i]."<br>";

Python (generally you iterate over lists in Python, instead of accessing by index):

lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
    print(str(item) + "<br>")

Example 2

for (i < 10 ; $i ++)
echo i] = $i +1 ;

Python:

lst = range(1, 11)
for item in lst:
    print(item)

Or maybe:

lst = []
for i in range(10):
    lst.append(i + 1)
    print(lst[-1])     # prints out last element

Example 3

$php = array(1,2,3,4,5,6,7,8,9,10);
foreach (value)
echo $value."<br>";

Same as 1st

Example 4

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

Python:

lst = [1, 2, 3, 4]
lst = [val * 2 for val in lst]

Example 5

$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach (key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

Python (note that {...} creates a dict [dictionary] in Python, not a list/):

dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.items():
    print("Key: %s; Value: %s<br />" % (key, value))

Example 6

$arr = array("one", "two","three");
while (list(value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

Python:

lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
    print("Key: %d; Value: %s<br />" % (key, value))

Example 7

$arr = array("one", "two","three");
while ($element = each($arr)) {
    echo "Key: $element['key']; Value: $element['value']<br />\n";
}

There is no direct Python equivalent to this.

Example 8

$products = array( array("ITL","INTEL","HARD"),
                        array("MIR", "MICROSOFT","SOFT"),
                        array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
                         );
for (row < 3; $row++)
{
    for ($col = 0; col++)
    {
        echo "|".$products[col];
    }
    echo "<br>";
}

Python:

products = [['ITL', 'INTEL', 'HARD'],
    ['MIR', 'MICROSOFT', 'SOFT'],
    ['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]

for product in products:
    for item in product:
        print('|' + item)
    print('<br>')

Or maybe a more Pythonic version:

for product in products:
    print('|%s<br>' % ('|'.join(product)))
2 of 4
10

"What is in Python?", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

Sorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.

Unless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.

Still not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad.

🌐
Reddit
reddit.com › r/phphelp › converting python dictionary into something php can use? associative array?
r/PHPhelp on Reddit: Converting python dictionary into something php can use? Associative Array?
February 20, 2017 -

I'm more comfortable with python than php, but I've worked with it a bit (plus a lot of asp) so I am used to the style. However I'm having trouble passing output from python to php.

My py creates a dictionary object

{'key1': 123, 'key2': 456, 'key3': 789}

My php then gets the output from that py file:

exec ('/usr/bin/python /var/www/html/data.py', $output);

foreach ($output as $item) {
        print_r($item);
}

This prints each dictionary entry to the page correctly. And each of these entries is what I need in a 'dictionary' type of object in php. I've seen references to an Associative Array, others saying to serialze with json.

Since I'm expecting to do more interactive work between python and php which way would be best? Is json the 'modern' way of doing it? Is it better form or more flexible to do this?

I'm looking for the right answer, not the quick copy and paste answer and I want to get better at this not just find a solution that fits today's need.

Thanks for any help that you can provide.

===========

edit: That was far easier than I expected. Here's what I'm doing now (basic usage example):

in the .py file, after getting all my results loaded into a dictionary object called 'results':

print json.dumps(results)

This is called in php like this (simple output function here, processing will come later):

$json = exec ('/usr/bin/python /var/www/html/data.py', $output);
$array = json_decode($json, true);

foreach($array as $item)
{
    print($item['timestamp']);
}

That gives me a page full of timestamps, just like I was hoping for. This was incredibly easy and knowing that it's compatible across languages is awesome.

Thanks for all the help and tips!

🌐
YouTube
youtube.com › watch
Converting PHP stdClass Objects to Arrays: Simplified Guide - YouTube
Summary: Learn how to convert PHP stdClass objects to arrays using built-in functions and techniques. Simplify your PHP development with these conversion met...
Published: August 27, 2024
Views: 112
🌐
GUVI
guvi.in › blog › full stack development › how to convert object to array in php (5 easy methods, 2026)
How to Convert Object to Array in PHP (5 Easy Methods, 2026)
September 16, 2026 - Request More Information · FULL STACK DEVELOPMENT · By Abhishek Pati · Sep 16, 2026 5 Min Read 2856 Views · (Last Updated) To convert object to array in PHP, you can use built-in functions like type casting, get_object_vars(), or json_decode() ...
🌐
Like Geeks
likegeeks.com › home › web development › cast or convert an array to object using php (hydrator pattern)
Cast or Convert an Array to Object Using PHP (Hydrator Pattern)
Convert an Array To Object Using PHP Hydrator Pattern and Object To Array All By PHP Reflection Functions and Pattern Matching For Getters and Setters
🌐
STechies
stechies.com › convert-php-object-array
How to Convert PHP object to array
An object is a specimen of class, which users use to define an individual data structure within a PHP class. PHP supports the conversion of an object into an array using the typecasting method and JSON Decode and Encode method.
🌐
TutorialsPoint
tutorialspoint.com › convert-object-to-an-array-in-php
Convert object to an array in PHP.
July 30, 2019 - An object is an instance of a class that has properties and methods, while an associative array uses string keys to store key−value pairs. Converting objects to arrays allows easier data manipulation and serialization. The json_encode() function converts a PHP value to JSON string, and json_decode() converts it back to a PHP array when used with the second parameter set to true −
🌐
GitHub
ocramius.github.io › blog › fast-php-object-to-array-conversion
Fast PHP Object to Array conversion
<?php class Foo { public $bar = 'barValue'; protected $baz = 'bazValue'; private $tab = 'tabValue'; } $foo = new Foo(); $arrayFoo = (array) $foo; var_dump($arrayFoo); ... array(3) { ["bar"]=> string(8) "barValue" ["*baz"]=> string(8) "bazValue" ["Footab"]=> string(8) "tabValue" } Weird, so $baz is copied to array key '*baz' and $tab is copied to Footab...
🌐
Techie Delight
techiedelight.com › home › java › convert an object to an array in php
Convert an object to an array in PHP | Techie Delight
July 7, 2026 - You may use Reflection to access private and protected fields outside the object’s scope. This example uses ReflectionClass::getProperties() to retrieve reflected properties and stores them in an array. Unlike type casting, this solution results in proper key names for non-public fields. Before PHP 8.1.0, you must call ReflectionProperty::setAccessible() to enable access to a protected or private property.
🌐
GeeksforGeeks
geeksforgeeks.org › php › convert-an-object-to-associative-array-in-php
Convert an object to associative array in PHP - GeeksforGeeks
July 11, 2025 - The get_object_vars() function returns an associative array containing the properties of the given object. ... <?php class car { /* Member variables */ var $make; var $model; var $year; function __construct($make, $model, $year) { $this->make ...