2016-07-12 4 views
0

Я разрабатываю конвертер валют с использованием PHP и Google Finance как часть своего класса проектирования системы.ошибка preg_match, конвертер валют, неопределенное смещение: 1

Можете ли вы помочь мне исправить ошибку:

"Примечание: Не определено смещение: 1"?

Вот код:

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

не нужно указывать '' $ from ',' $ to'' – Ghost

+0

Hi @Ghost. Это чувство, когда вы разобрались в одиночных цитатах. Большое спасибо. –

ответ

1

Наслаждайтесь!)

<?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"; 
} 

Объяснение: '$to' не равна $to потому 'strings in quotes' не разбор на PHP двигателя, только в "double quotes". Вот почему ваш запрос ошибочен, и file_get_contents получил еще один документ с ошибкой. Итак, preg_match вернул false и $converted был пустым массивом. Вот почему попытка получить $converted[1] называется уведомлением.

Удачи вам!