Jump to content

Passing the contents of a SimpleXml generated array to javascript


bluebomber
 Share

Recommended Posts

Hello, I've had success passing over the contents of a manually defined PHP array into a javascript array by using "implode" to move the array into a single string which is then written out as a javascript statement using echo - however I'm having trouble getting this to work with an array created from an xml file using Simplexml.The method I've been using to pass over manually defined array is as follows:<?php$cars[0]="Saab";$cars[1]="Volvo";etc...$single = implode("', '", $cars);echo "<script type='text/javascript'>jsarray = new Array('$single');</script>";?>The problem I have is when dealing with my XML file - the information I want to extract are a series of titles - the following is a quick example of how my XML file looks:<?xml version="1.0" encoding="iso-8859-1"?><option1> <image> <title>Last Week</title> <filename>photos/1.jpg</filename> <thumb>tn/1.jpg</thumb> </image> <image> <title>Summer</title> <filename>photos/2.jpg</filename> <thumb>tn/2.jpg</thumb> </image>etc...<option1>I can access any title in the image array by using:$xml->image[n]->title;However I have no idea how to implode the contents of all those titles into one string so I can pass it over and insert it into a javascript variable as I have done in the first example.Can anyone help me here?

Link to comment
Share on other sites

First, look into using JSON, you can convert a PHP array directly to the equivalent Javascript array, and vice-versa. PHP has json_encode and json_decode functions for that.If you can access each title, then it makes sense to create an empty array that you add each title to, and at the end you can write it out to Javascript.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...