Kilise
Kilise

Reputation: 1089

From XML to PHP to Array to JSON Object

As the title says, I got a Xml file and reading the values in php and saves them in an array. My array works perfectly in PHP.

I can return my values one by one just by taking them from the array:

echo myArray[0][1];

Which will return: text

This is a var_dump:

array (size=2)
  0 => 
    array (size=5)
      0 => 
        object(SimpleXMLElement)[13]
          string 'text' (length=47)
      1 => 
        object(SimpleXMLElement)[14]
          string 'lol' (length=22)
      2 => 
        object(SimpleXMLElement)[15]
          string 'hehe' (length=8)
      3 => 
        object(SimpleXMLElement)[16]
          string 'thanks' (length=4)
      4 => null
  1 => 
    array (size=5)
      0 => 
        object(SimpleXMLElement)[17]
          string 'texxtttttttt' (length=34)
      1 => 
        object(SimpleXMLElement)[18]
          string 'text here' (length=16)
      2 => 
        object(SimpleXMLElement)[19]
          string 'alots of text i guess' (length=44)
      3 => 
        object(SimpleXMLElement)[20]
          string 'some more text' (length=23)
      4 => 
        object(SimpleXMLElement)[21]
          string 'some text here' (length=14)

Now to the problem.

var obj= <?php print json_encode($myArray); ?>;

I can't get the values one by one anymore. I've tried to loop it and put the values in an Array again

            var questions = new Array();
            $.each(obj , function(k, v) {  
                    $.each(v, function(k2, v2) {
                        $.each(v2, function(k3, v3) {
                              questions[k2] = v3;
                        });       
                    });
                });

This doesn't give me the result that I want. What I need is to save the values one by one like i did in the array in php ( myArray[0][1]; ) Anyone?

Upvotes: 1

Views: 334

Answers (1)

nirazul
nirazul

Reputation: 3955

So you want to write PHP Code into a Javascript file? I heavily discourage that. Split your code into a PHP only file that does nothing except json-encoding your array:

<?php print json_encode($myArray); ?>;

In your JS-File you start an ajax request to get the string from your PHP file. jQuery has convenient methods for exactly that:

jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] )

Here's another resource that shows more complex alternatives: Ajax Query to get JSON

Upvotes: 1

Related Questions