Jump to content

creating array from string value


prakash

Recommended Posts

Hi,

 

I have to fetch data from another site and store it in array on my page.

For that I used file_get_contents function to get page contents:

 

<?php
$testData=file_get_contents('http://www.test.com/service_data.php');
print $testData;
?>

 

The variable $testData gets string data like

 

array(array( field_1=>"AAA", field_2=>"111" ), array( field_1=>"BBB", field_2=>"222" ), array( field_1=>"CCC", field_2=>"333" ))

 

So I need to convert the output into array.

 

When I try to print following I am getting error like "Fatal error: Cannot use string offset as an array in..." 

print $testData[0][field_1];

 

So how can I correct this error?

 

I tried to use SOAP but I am newbie to it so I don't understand the process for creating SOAP Server so that I can fetch data on my code easily.

 

Can anyone let me know the easiest and standard way to fetch data in my case?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/143600-creating-array-from-string-value/
Share on other sites

You can parse it.

 

<?php
$testData = 'array(array( field_1=>"AAA", field_2=>"111" ), array( field_1=>"BBB", field_2=>"222" ), array( field_1=>"CCC", field_2=>"333" ))';

$data = explode(" ), array( ", $testData);
$data[0] = str_replace("array(array( ", "", $data[0]);
$data[(count($data)-1)] = str_replace(" ))", "", $data[(count($data)-1)]);
$newArray = array();
$i=0;
foreach ($data as $dat) {
$fields = split(", ", $dat);
$newArray[$i] = array();
foreach ($fields as $field) {
	list($key, $val) = explode("=>", $field);
	$newArray[$i][$key] = str_replace('"', "", $val);
}
$i++;
}

print_r($newArray);
die();
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.