Json response with php - php

I am trying to get JSON response using PHP. I want to have Json array not the HTML tags. But the output shows HTML tags as well.I want to remove this HTML output! PHP code is as follows: I don't know how to do this ? Please help.
Thanks in advance :)
<?php
function getFixture(){
$db = new DbConnect();
// array for json response of full fixture
$response = array();
$response["fixture"] = array();
$result = mysql_query("SELECT * FROM fixture"); // Select all rows from fixture table
while($row = mysql_fetch_array($result)){
$tmp = array(); // temporary array to create single match information
$tmp["matchId"] = $row["matchId"];
$tmp["teamA"] = $row["teamA"];
$tmp["teamB"] = $row["teamB"];
array_push($response["fixture"], $tmp);
}
header('Content-Type: application/json');
echo json_encode($response);
}
getFixture();
?>

It's difficult to tell without seeing what your output is, but there is nothing in your code which would add HTML to your response.
It sounds like the HTML is in the database, so you're getting the data as expected, and your browser is the displaying whatever html elements might be there.
You could ensure none of the rows from the database have HTML in them by using strip_tags as follows:
$tmp["teamA"] = strip_tags($row["teamA"]);
Do this for all rows which may contain html.
Sorry if this is not formatted right, I'm new to StackOverflow!
http://php.net/strip-tags

Related

Trouble outputting json to php

One of my sources for data recently changed how they are providing a json file to me, they added something before the actual output, and I am having trouble getting the values to display on my landing page.
Old json output
string(6596) "[{"id":239,"solution_id":3486," etc...
New json output
string(6614) "{"picker_offers":[{"id":239,"solution_id":3486," etc...
For my landing page I am using the following:
$datastream = json_decode($result);
foreach($datastream as $component) {
$productid = $component->id;
I was able to successfully output the data to php from their old output, but I am not sure how to get around the value "picker_offers" that is being passed as part of the json file, but it isn't part of the actual data to output.
How can I not include that "picker_offers", or what can I do to be able to read the data? With this new output there is an extra curly bracket wrapper called "picker_offers" around the entire output.
Thank you very much
Solution 1 : if you want to remove picker_offers
$datastream = json_decode($result);
$picker_offers = $datastream->picker_offers;
unset($datastream->picker_offers);
$datastream = $picker_offers;
foreach($datastream as $component) {
$productid = $component->id;
}
Solution 2 : if you don't want to remove picker_offers
$datastream = json_decode($result);
foreach($datastream->picker_offers as $component) {
$productid = $component->id;
}

json encode using php not able to get [] brackets

here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]

Store XML Data to MySQL

I have an XML file. I want to save all the data from the XML file to the database
The file structure of XML is like
<STORY>
<BYLINE>abc</BYLINE>
<STORYID>123456</STORYID>
</STORY>
The code for storing data to database that I am using is
$dom = new DOMDOcument();
$dom->loadXML(equitymarketnews/$zname);
$xpath = new DOMXpath($dom);
$res = $xpath->query("//STORY/");
$allres = array();
foreach($res as $node){
$result = array();
$byline = mysql_real_escape_string($node->getElementsByTagName("BYLINE")->item(0)->nodeValue);
$storyid = mysql_real_escape_string($node->getElementsByTagName("STORYID")->item(0)->nodeValue);
}
$sql12="insert into equitymarketnews values('$byline','$storyid')";
mysql_query($sql12);
I am getting nothing in my database. All values are blanks.
Where am I going wrong?
I think something is wrong with this line
$res = $xpath->query("//STORY/");
i want to story the data ie ABC and 12345 FROm XML File To Table in database
I don't really know what your question is but assuming that the code you posted does not work as you aspect, one thing i noticed is the insertion of the record:
$sql12="insert into equitymarketnews values('$byline','$storyid','$pubdate','$author','$cat','$subcat','$titleline','$subtitleline,'$storymain','$flag')";
mysql_query($sql12);
shouldn't it be inside your foreach loop? Otherwise you won't get anything into your database.
In my opinion it should look something like that:
foreach($res as $node){
$result = array();
$byline = mysql_real_escape_string($node->getElementsByTagName("BYLINE")->item(0)->nodeValue);
$storyid = mysql_real_escape_string($node->getElementsByTagName("STORYID")->item(0)->nodeValue);
$sql12="insert into equitymarketnews values('$byline','$storyid')";
mysql_query($sql12);
}
You can actually use mysql client directly for importing XML data. I do not have much experience to provide you with a code sample, but MySQL docs have quite a bit documentation on it.
Essentially, you can do something like this:
LOAD XML LOCAL INFILE 'address.xml' INTO TABLE quitymarketnews ROWS IDENTIFIED BY '<STORY>';

JSON PHP: Is this the correct way?

I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.
What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".
Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.

A weird result, as a result of this PHP script

require_once 'include/BestBuy/Service/Remix.php';
$skuid = rawurldecode($_GET['skuid']);
$apiKey = 'tfvs7h89pwn4pzmyj9nxemmg'; // Your API key
$remix = new BestBuy_Service_Remix($apiKey);
$result = $remix->product('$skuid','json')
->show(array('url'))
->query();
$data = json_decode ($result, true);
$feed = $data['url'];
print <<< FEEDS
$feed
FEEDS;
When I put this script into my page, the $feed will echo the current URL.
But when I manually supply the script with an integer, replacing ($skuid) it will be successful.
It's really weird, But I think it has something to do with me using a variable in that specific array.
And it is also weird, because It was working before I re arranged some of the HTML.
I'm trying to approach this problem the most logical way.
Please help.
Thanks.
should you have $skuid in quotes? I would expect:
$result = $remix->product($skuid,'json')
rather than
$result = $remix->product('$skuid','json')

Categories