1

I have downloaded what looks like a PHP array file, and wondering if there is a python module or another way of converting/importing the array to a python dictionary. Here is a sample of the start of the PHP array file.

<?php

$legendre_roots = array();

$legendre_roots[2] = array(
-0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168,
0.5773502691896257645091487805019574556476017512701268760186023264839776723029333456937153955857495252252087138051355676766566483649996508262705518373647912161760310773007685273559916067003615583077550051041144223011076288835574182229739459904090157105534559538626730166621791266197964892168);

I would ideally like a dictionary with for example:

legendre_roots = { 2: [-0.57735,0.57735], 3: [.......]......}

Any help appreciated.

2
  • @Huey: array is an ordered dictionary. Commented Jan 28, 2014 at 10:38
  • I am not familiar with PHP so can't say if there are. I do have knowledge of python though, and would just like to convert the above example to a dictionary in python. Commented Jan 28, 2014 at 10:44

3 Answers 3

4

AN EXAMPLE

<?php
$arr = array('test' => 1, 'ing' => 2, 'curveball' => array(1, 2, 3=>4) );
echo json_encode($arr);
?>

# elsewhere, in Python...
import simplejson
print simplejson.loads('{"test":1,"ing":2,"curveball":{"0":1,"1":2,"3":4}}')
Sign up to request clarification or add additional context in comments.

1 Comment

OK. I have the php file on disk. Do i just import the php file as text adding the echo statement, import the simplejson module and print the loaded text object using simplejson.loads?
1

Add to the PHP code a small snipet which JSON encodes the array, and displays / stores it on the disk.

echo json_encode($legendre_roots)

You can probably use that JSON code directly. if not, decode it in python and pprint it.

6 Comments

Sorry. I am not familiar with PHP or JSON. What do you mean by a small snipet, and how do you 'decode'?
1) modify the code. 2) as I said, probably not necessary. left as an exercise: search for python decode json
Do I add the json snipet to end of every legendre_roots such as ` legendre_roots[???] = array(?????) echo json_encode($legendre_roots); ` or to the end of the file. There are numerous sections ending with '????);`
I have educated myself a bit on the json format and added the bit to the end of the file. I then imported the file using obj = open('file.php') after which I tried to decode the object using import json then json.load(obj). I comes up with an error: ValueError: No JSON object could be decoded. Please help here. I really don't want to spend days on this. I even tried it without the snippet added to the end of the file with the same error.
I ran my php file through a json validator link as suggested on some sites and it bombs out on the 1st line: Parse error on line 1: <?php$legendre_roots ^ Expecting '{', '['
|
0

After deciding I don't have the time to mess with JSON and PHP intricacies I decided to write a python script to do the job. It is based on pure textual processing and can be adapted by other if needed. sic:

#!/usr/bin/python

''' A file that will read the text in the php file and add each array as 
a dictionary item to a dictionary and saves it as a dictionary.
'''
import pickle
import pdb

file_name = 'lgvalues-abscissa.php'
#file_name = 'lgvalues-weights.php'
text = 'legendre_roots['
#text = 'quadrature_weights['


def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False

mydict = dict()
lst = []
ft = open(file_name,'rt')
file_lines = ft.readlines()
for i, l in enumerate(file_lines):
  if l.find(text) != -1:
    key = l.split()[0]
    key = [key[l.find('[')+1:l.find(']')],]
    continue
  if is_number(l.strip()[:16]): 
    lst.append(float(l.strip()[:16]))
    if l.strip()[-2:] == ');':
      if int(key[0]) != len(lst):
        print 'key %s does not have the right amount of items.'\
            %(key[0])
      tempdict = {}
      tempdict = tempdict.fromkeys(key,lst)
      mydict.update(tempdict)

      lst = []

file_name = file_name[:-4]+'.dat'
fb = open(file_name,'wb')
pickle.dump(mydict,fb)
print 'Dictionary file saved to %s' % (file_name)
fb.close()

Yes it is very specific to my case but may help someone out there if they have the time to adapt the code and don't get much help with PHP JSON otherwise.

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.