extract data into json - php

I retrieved MySQL data from three tables in XML using PHP:
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$doc = new DomDocument('1.0');
$root = $doc->createElement('recipes');
$root = $doc->appendChild($root);
while($row = mysql_fetch_assoc($resouter)){
$outer = $doc->createElement($table_first);
$outer = $root->appendChild($outer);
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $outer->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}// foreach
//while
$table_second='instructions';
$query="SELECT instructions.instruction_id,instructions.instruction_text FROM $table_second where rec_id = ".$row['rec_id'];
$resinner=mysql_query($query, $conn);
$inner = $doc->createElement($table_second);
$inner = $outer->appendChild($inner);
while($row1 = mysql_fetch_assoc($resinner)){
$inner1=$doc->createElement('instruction');
$inner1=$inner->appendChild($inner1);
foreach ($row1 as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $inner1->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} // foreach
}// while
$table_third='ingredients';
$query="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM $table_third where rec_id = ".$row['rec_id'];
$resthird=mysql_query($query, $conn);
$inner=$doc->createElement($table_third);
$inner=$outer->appendChild($inner);
while($row=mysql_fetch_assoc($resthird)){
$inner2=$doc->createElement('ingredient');
$inner2=$inner->appendChild($inner2);
foreach($row as $fieldname=> $fieldvalue)
{
$child=$doc->createElement($fieldname);
$child=$inner2->appendChild($child);
$value=$doc->createTextNode($fieldvalue);
$value=$child->appendChild($value);
}
}
}
mysql_close($conn);
$xml_string = $doc->saveXML();
echo $xml_string;
?>
This works perfectly, but now I want to retrieve that data in JSON. I retrieved data from one table using JSON, but how to retrieve the same data from these three tables using JSON instead of XML?

Create arrays in PHP and use json_encode() on your structure.

Related

Parsing Json with a multidimensional array/object. PHP

I am trying to parse a JSON file for the first time ever and insert the information into my database. The problem is that this object/array is multidimensional, so $number = stats[0] is getting values on each level of the array. This is a link to the JSON file. I want to avoid everthing but the data: values that I exploded with PHP. Here is a link to my output right now. If you look at my output, I am only interested in the 8,C,J. Pavelski and 26. Those are the values I want in my database.
$json = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$stats = explode(",", $val);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
echo $number." ".$position." ".$name." ".$points."<br />";
/* $query = "INSERT INTO stats2015_2016 ('number','position','name','gp','goals','assists','points','plsmns','pim','shots', 'toi', 'pp', 'sh', 'gwg', 'ot')
VALUES ('$number','$position','$name','$gp','$goals','$assists','$points','$plsmns','$pim','$shots','$toi','$pp','$sh','$gwg','$ot')";
$result= $db->query($query); */
}
Thank you
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$sk = explode(',', $d['data']);
$number = $sk[0];
$position = $sk[1];
$name = $sk[2];
$points = $sk[6];
echo $number." ".$position." ".$name." ".$points."<br />";
}
repeat for goalie data as required

Using urldecode on a mysql_fetch_array Array

I have been trying to convert the fields from a mysql_fetch_array (that are urlencoded) to urldecode before converting to JSON (json_encode)
Here's what I'm working with that doesn't work:The output is still urlencoded
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_fetch_array(mysql_query($query));
foreach($result as $value) {
$value = urldecode($value);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
Any ideas?
yeah....! you're not updating $result with the value returned by the function. $value needs to be passed by reference.
foreach($result as &$value) {
$value = urldecode($value);
}
or
foreach($result as $i => $value) {
$result[$i] = urldecode($value);
}
when you do this...
foreach($result as $value) {
$value = urldecode($value);
}
The result of the function is lost at at iteration of the foreach. You're trying to update each value stored in $result but that's not happening.
Also take note that the code only fetches one row from your query. I'm not sure if that's by design or not.
Try:
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_query($query);
$value = array();
while($row = mysql_fetch_array($result))
$value[] = urldecode($row);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));

how to update mysql table from Serialised json?

I have get Serialised from Nestable, but I don't know how to write php code update my database like wordpress:
$data = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
function extract_value($value,$order=0){
if(is_array($value)){
foreach($value as $k => $v){
echo "UPDATE vod_page_menu SET ordering = '$order', parent_id = '$v' WHERE id = '$v'; <br/>";
extract_value($v,$order+1);
}
}
}
$json = json_decode($data,true);
extract_value($json);
You need to first decode the JSON, then you can use it in PHP:
$data = json_decode($data, true);
foreach ($data as $id => $value) {
...
}
function extract_value($array,$parent=0,$i=1){
foreach($array as $k => $v) {
$id = $array[$k]['id'];
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$parent' WHERE id = '$id'; <br/>";
if(isset($array[$k]['children'])){
$children = $array[$k]['children'];
foreach($children as $key => $obj){
$child = $children[$key]['id'];
$i++;
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$id' WHERE id = '$child'; <br/>";
if(isset($children[$key]['children']))
extract_value($children[$key]['children'],$child,++$i);
}
}
$i++;
}
}

SimpleXML node with spaces and equal signs in the node name

I have an xml document that contains spaces and equal signs in the node names. I'm trying to use SimpleXML to extract the data from those nodes but it returns blank no matter what I try.
A sample of the xml document
<code><away>
<radio>url.here</radio>
<live bitrate="1">url.here</live>
<live bitrate="0">url.here</live>
</away></code>
I have tried using bothecho "<td>".$node->away->{'live bitrate="1"'}."</td>";
echo "<td>".$node->away->{'live'}->{'bitrate="1"'}."</td>";
Here is a function I use to convert the SimpleXML object to an array:
public function simpleXMLToArray($xml,
$flattenValues=true,
$flattenAttributes = true,
$flattenChildren=true,
$valueKey='#value',
$attributesKey='#attributes',
$childrenKey='#children'){
$return = array();
if(!($xml instanceof SimpleXMLElement)){return $return;}
$name = $xml->getName();
$_value = trim((string)$xml);
if(strlen($_value)==0){$_value = null;};
if($_value!==null){
if(!$flattenValues){$return[$valueKey] = $_value;}
else{$return = $_value;}
}
$children = array();
$first = true;
foreach($xml->children() as $elementName => $child){
$value = $this->simpleXMLToArray($child, $flattenValues, $flattenAttributes, $flattenChildren, $valueKey, $attributesKey, $childrenKey);
if(isset($children[$elementName])){
if($first){
$temp = $children[$elementName];
unset($children[$elementName]);
$children[$elementName][] = $temp;
$first=false;
}
$children[$elementName][] = $value;
}
else{
$children[$elementName] = $value;
}
}
if(count($children)>0){
if(!$flattenChildren){$return[$childrenKey] = $children;}
else{$return = array_merge($return,$children);}
}
$attributes = array();
foreach($xml->attributes() as $name=>$value){
$attributes[$name] = trim($value);
}
if(count($attributes)>0){
if(!$flattenAttributes){$return[$attributesKey] = $attributes;}
else{$return = array_merge($return, $attributes);}
}
return $return;
}

Structure of php JSON output

this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...

Categories