I am not able to display data from this url using php json decode:
https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it
here is the data provider:
https://mymemory.translated.net/doc/spec.php
thanks.
What I want is to setup a form to submit words and get translation back from their API.
here is my code sample:
<?php
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
// parse the JSON
$data = json_decode($json);
// show the translation
echo $data;
?>
My guess is that you might likely want to write some for loops with if statements to display your data as you wish:
Test
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
if (isset($data["responseData"])) {
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html = $value;
} else {
continue;
}
}
} else {
echo "Something is not right!";
}
echo $html;
Output
Ciao Mondo!
<?php
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
';
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html .= '<p>' . $value . '</p>';
} else {
continue;
}
}
$html .= '
</body>
</html>';
echo $html;
?>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
<p>Ciao Mondo!</p>
</body>
After many researches I got it working this way:
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');
$obj = json_decode($json);
echo $obj->responseData->translatedText;
thank you all.
Related
How can I loop values in controller send it to view in CodeIgniter
I have tried with below code
Controller
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
}
}
View
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo $d->invoice_id;
?>
</body>
</html>
But data is not printing in the view.How can I print the values??
You Can't foreach and pass the data to view.
public function getdata()
{
$result = $this->Mdi_download_invoices->download_pdf_files(12);
$data['d'] = $result;
$this->load->view('download_all_invoices/pdf',$data);
}
Note: Since you're using echo $d->invoice_id; check whether your result object (row, result)
I think you are looking for this :
<?php
public function getdata()
{
$data = $this->Mdi_download_invoices->download_pdf_files(12);
foreach ($data as $d)
{
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('download_all_invoices/pdf',$d,true);
$mpdf->WriteHTML($html);
$mpdf->Output($estructure.$d->invoice_id,'F');
$this->load->view('download_all_invoices/pdf',$d);
}
}
?>
How can I get variables "price_usd" for bitcoin & ethereum from JSON url https://api.coinmarketcap.com/v1/ticker
This works:
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
$lastPrice = $json[0]["price_usd"];
echo $lastPrice;
However, I would like to do something like this:
<?php
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
function price($ticker) {
foreach($json[] as $item) {
if($item->id == $ticker) {
echo $item->price_usd;
}
}
}?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo price("bitcoin");?>
<?php echo price("etheruem");?>
</body>
</html>
You can use array_column for this:
$json = json_decode($fgc, TRUE);
// following line will create assoc array as key => value for 'price_usd' as key and 'id' as value
$js = array_column($json, 'price_usd', 'id');
echo $js["bitcoin"];
General Function:
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
function price($curr) {
global $decoded_json;
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
echo price("bitcoin");
echo price("ethereum");
Another solution without global var:
// this will create a new request to api.coinmarketcap.com on each call
function price($curr) {
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
Now that the question is updated, you can just cast the $js to object and use it like an object:
$js = (object) $js;
echo $js->bitcoin;
file_get_htm return false, but if i try get data to string, then everything is ok ..
$url = "http://www.dkb-handball-bundesliga.de/de/dkb-hbl/spielplan/spielplan-chronologisch/";
$output = file_get_contents($url);
print_r($output); //this return string
$html = file_get_html($url);
print_r($html); //this return false
i was try with curl, but everything is the same...
if i cgange url for example, everything work ok...
$url='http://www.dkb-handball-bundesliga.de/de/s/spiele/2014-2015/dkb-handball-bundesliga/1--spieltag--bergischer-hc-vs-sg-bbm-bietigheim/';
You will get data from this:
<?php
// put your code here
include_once './simple_html_dom.php';
$html = file_get_html("http://www.dkb-handball-bundesliga.de/");
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
?>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<table>
<tr>
<th>My elements</th>
Hello world 1
Hello world 2
Hello world 3
Hello world 4
Hello world 5
</tr>
</table>
</body>
</html>
<?php
// You need to know the location of the file that you are calling.
include_once './simple_html_dom.php';
$html = file_get_html("http://localhost/PhpHelpers/examples.html");
$links = array();
foreach($html->find('a') as $key => $val) {
$links[$key] = $val;
}
print_r($links);
?>
I have read and tried every POST about this but cannot get it to work.
This is the HTML:
<meta itemprop="interactionCount" content="UserPlays:4635">
<meta itemprop="interactionCount" content="UserLikes:4">
<meta itemprop="interactionCount" content="UserComments:0">
I need to extract the '4635' bit.
Code:
<?php
$html = file_get_html($url);
foreach($html->find("meta[name=interactionCount]")->getAttribute('content') as $element) {
$val = $element->innertext;
echo '<br>Value is: '.$val;
}
I get nothing back?
$metaData= '<meta itemprop="interactionCount" content="UserPlays:4635">
<meta itemprop="interactionCount" content="UserLikes:4">
<meta itemprop="interactionCount" content="UserComments:0">';
$dom = new DOMDocument();
$dom->loadHtml($metaData);
$metas = $dom->getElementsByTagName('meta');
foreach($metas as $el) {
list($user_param,$value) = explode(':',$el->getAttribute('content'));
// here check what you need
print $user_param.' '.$value.'<br/>';
}
// OUTPUT
UserPlays 4635
UserLikes 4
UserComments 0
include 'simple_html_dom.php';
$url = '...';
$html = file_get_html($url);
foreach ($html->find('meta[itemprop="interactionCount"]') as $element) {
list($key, $value) = explode(':', strval($key->content));
echo 'Value:'.$value."\n";
}
I have found the script.
http://www.aota.net/forums/showthread.php?t=24155
My lang.php
<?php
$Lang = array(
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
My edit.php
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
unset($_POST['submit']); // remove the submit button from the name/value pairs
$new_array = ""; // initialize the new array string (file contents)
$is_post = true; // set flag for use below
// add each form key/value pair to the file
foreach (array_keys($_POST) as $key)
{ $new_array .= "\$Lang[\'$key\'] => \"".trim($_POST[$key])."\",\n"; }
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
}
// write a file
function write_file($filename, $contents)
{
if (! ($file = fopen($filename, 'w'))) { die("could not open $filename for writing"); }
if (! (fwrite($file, $contents))) { die("could not write to $filename"); }
fclose($file);
}
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value)
{
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"": "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>
Unfortunately I can not read array and Keys from lang.php.
Script writer, writes:
all lines in array.txt did do set $ Bid [] will be lost.
But I want lang.php after the change save as a PHP file that would go?
I want to create a drop-down list and load array with matching keys, change key text and save.
I thank you in advance for your help!
You shouldn't read lang.php file.
You should include it.
Better way:
require_once('lang.php'); // or require_once($array_file);
and remove these lines:
// read the array into $Lang[]
$file_lines = file($array_file);
$Lang = array();
foreach ($file_lines as $line)
{
list($b4_key, $key, $b4_value, $value) = explode('"', $line);
if (preg_match("/Lang/", $b4_key))
{ $Lang[$key] = $value; }
}
# # # # # # # #
As I understand your file contents only one language, doesn't it?
If no, will be a little modifications in the code.
<?
// edit the values of an array ($Lang["key"] = "value";) in the file below
$array_file = "lang.php";
// if POSTed, save file
if (isset($_POST['submit'])) {
unset($_POST['submit']); // remove the submit button from the name/value pairs
$is_post = true; // set flag for use below
// write over the original file, and write a backup copy with the date/time
write_file($array_file, $new_array);
write_file($array_file . date("_Y-m-d_h-ia"), $new_array);
file_put_contents($array_file, serialize(array(
'timestamp' => time(), // after you can display this value in your preffered format
'data' => serialize($_POST)
)));
}
$Lang_content = #unserialize(#file_get_contents($array_file));
if (!array_key_exists('data', $Lang_content)) {
$Lang_content = array(
'timestamp' => 0, // or time()
'data' => serialize(array())
);
}
$Lang_template = array( // If you want
'TEXT' => "baer",
'GRET' => "hallo",
'FACE' => "face",
'HAPY' => "happy",
'TOOL' => "tool",
);
$Lang = array_merge(
$Lang_template,
unserialize($Lang_content['data'])
);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Language Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1><?= $array_file ?></h1>
<? if (!isset($is_post)) { ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<? } ?>
<table>
<?
// loop through the $Lang array and display the Lang value (if POSTed) or a form element
foreach ($Lang as $key => $value) {
echo "<tr><td>$key</td><td>";
echo isset($is_post) ? "= \"$value\"" : "<input type=\"text\" name=\"$key\" value=\"$value\">";
echo "</td></tr>\n";
}
?>
</table>
<? if (!isset($is_post)) { ?>
<p><input type="submit" name="submit" value="Save"></p>
</form>
<? } ?>
</body>
</html>