1

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?

1 Answer 1

1

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

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

1 Comment

Actually fixed it by changing the each function to: $.each(obj, function(k, v) { document.write(v[0][0] + "<br>") document.write(v[1][0] + "<br>") document.write(v[2][0] + "<br>") document.write(v[3][0] + "<br>") if(v[4]) document.write(v[4][0] + "<br>") });

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.