2016-07-12 3 views
0

Ich entwickle einen Währungsumrechner mit PHP und Google Finanzen als Teil meiner System-Design-Klasse.preg_match Fehler, Währungsumrechner, undefined Offset: 1

Können Sie mir helfen, den Fehler zu beheben:

"Notice: Undefined offset: 1"? Hier

ist der Code:

HTML

<form action="" method="POST"> 
Amount: 
<input type="text" name="amount" /><br/><br/> 
From: 
<input type="text" name="from" /><br/><br/> 
To: 
<input type="text" name="to" /><br/><br/> 
<input type="submit" id="convert" name="convert"/> 
</form> 

PHP

<?php 

function currency_convert($amount, $from, $to){ 
    $url='https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to; 
    $data = file_get_contents($url); 
    preg_match("/<span class=bld>(.*)<\/span>/",$data,$converted); 
    echo $converted[1]; 
} 

if(isset($_POST['convert'])){ 
    $amount=$_POST['amount']; 
    $from=$_POST['from']; 
    $to=$_POST['to']; 
    currency_convert($amount, '$from', '$to'); 
} 

?> 
+0

muss nicht zitiert werden "$ from", "$ to" – Ghost

+0

Hi @ Ghost. Dieses Gefühl, wenn Sie von einzelnen Zitaten gepackt werden. Vielen Dank. –

Antwort

1

Viel Spaß!

)
<?php 

function currency_convert($amount, $from, $to){ 
    $url = 'https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from . '&to=' . $to; 
    $data = @file_get_contents($url); 
    if (!$data) { 
     return null; 
    } 
    if (!preg_match("/<span class=bld>(.*)<\/span>/", $data, $converted)) { 
     return null; 
    } 
    $converted = explode(' ', $converted[1], 2); 
    return (float)$converted[0]; 
} 

if(isset($_POST['convert'])){ 
    $convertedAmount = currency_convert($_POST['amount'], $_POST['from'], $_POST['to']); 
    echo $_POST['amount'] . ' ' . $_POST['from'] . ' = ' . number_format($convertedAmount, 2, '.', ' ') . ' ' . $_POST['to'] . "\n"; 
} 

Erläuterung: '$to' ist nicht gleich $to weil 'strings in quotes' nicht von PHP-Engine-Parsing, nur in "double quotes". Deshalb ist Ihre Anfrage falsch und file_get_contents hat ein anderes Dokument mit Fehler erhalten. So, preg_match gab false zurück und $converted war ein leeres Array. Deshalb versuchen, $converted[1] genannt zu bekommen.

Viel Glück!