2016-02-16 2 views
1

Я пытаюсь создать простой chatbot в HTML/PHP/XML. «Мозг» построен в XML. Форма html будет отправлена ​​через AJAX, который делает вызов searchBrain.php. Проблема в том, что когда вы отправляете форму, searchBrain не запрашивает мой файл brain.xml. Может ли кто-нибудь мне помочь?Запрос XPath не возвращает ответ

brain.xml

<?xml version="1.0" encoding="UTF-8"?> 
<brain> 
    <neuron> 
     <id>1</id> 
     <input>wie ben jij?</input> 
     <code></code> 
     <output>Ik ben Skye</output> 
     <keywords>wie,ben,jij,Wie,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>2</id> 
     <input>hoe gaat het?</input> 
     <code></code> 
     <output>Met mij gaat het goed. Hoe gaat het me u?</output> 
     <keywords>hoe,gaat,het,Hoe,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>3</id> 
     <input>wat ben jij?</input> 
     <code></code> 
     <output>Ik ben het laatste resultaat in kunstmatige intelligentie die de functies van het menselijk brein kan reproduceren met een grotere snelheid en nauwkeurigheid.</output> 
     <keywords>wat,ben,jij,Wat,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>4</id> 
     <input>hoe zie jij er uit?</input> 
     <code></code> 
     <output></output> 
     <keywords>hoe,zie,jij,er,uit,Hoe,?</keywords> 
     <image><!-- insert binary.jpg from imgLib --></image> 
    </neuron> 
    <neuron> 
     <id>5</id> 
     <input>stel jezelf even voor</input> 
     <code></code> 
     <output>Hoi ik ben Skye, ik ben online gegaan op 17-02-2016.Ik ben het laatste resultaat in kunstmatige intelligentie die de functies van het menselijk brein kan reproduceren met een grotere snelheid en nauwkeurigheid.</output> 
     <keywords>stel,jezelf,even,voor</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>6</id> 
     <input>Welke dag is het vandaag?</input> 
     <code><!-- PHP code om huidige dag weer te geven --></code> 
     <output>Vandaag is het </output> 
     <keywords>welke,dag,is,het,vandaag,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>7</id> 
     <input>wanneer ben je jarig?</input> 
     <code></code> 
     <output>Ik ben online gegaan op 17 Februari, dus ik ben jarig op 17 Februari :-)</output> 
     <keywords>wanneer,ben,je,jarig,?</keywords> 
     <image><!-- jarig.jpeg from imgLib --></image> 
    </neuron> 
</brain> 

searchBrain.php

<?php 

    //Create DOMDocument based on XML 
    $dom = new DOMDocument(); 

    // We don't want to bother with white spaces 
    $dom->preserveWhiteSpace = false; 

    //Load brain.xml 
    $dom->Load('brain.xml'); 

    //Get POST value 
    $sentence = $_POST['sentence']; 

    //Lowercase the XML so non case sensitive search is possible 
    $xml = strtolower($xml); 

    //Create XPath based on the DOM Document to search it 
    $xpath = new DOMXpath($dom); 

    //Define keywords for search 
    $searchKeywords = array($sentence); 

    //Iterate all of them to make them into valid XPath 
    $searchKeywords = array_map(
    function($keyword){ 
     //Replace any single quotes with an escaped single quote 
     $keyword = str_replace('\'','\\\'',$keyword); 
     return 'contains(.,\''.$keyword.'\')'; 
    }, 
    $searchKeywords 
    ); 

    //Implode all the keywords using and, could 
    //be changed to be an "or" condition if needed 
    $searchKeywords = implode(' and ',$searchKeywords); 

    //The search keywords now look like contains(.,'good') and 
    //contains(.,'hello') 

    //Search for any neuron tag that contains the text 
    //submitted by the from 
    $nodes = $xpath->query('//keywords['.$searchKeywords.']'); 

    //Iterate all nodes 
    foreach($nodes as $node){ 
     //Find the output node an print its content 
     var_dump($xpath->query('output',$node)->item[3]->textContent); 
    } 

?> 

И index.php

<!DOCTYPE html> 
<head> 
    <title>Skye</title> 
    <script src="jquery-2.1.4.js"></script> 

    <script> 
    $(document).ready(function() { 
     $("#Skye").submit(function(e){ 
      var url = "searchBrain.php"; 

      $.ajax({ 
       type: "POST", 
       url: url, 
       data: $("#Skye").serialize(), 
       success: function(response){ 
        $("#result").html(response); 
        //alert(response); 
       } 
      }); 
      e.preventDefault(); 
     }); 
    }); 
    </script> 

    <link rel="stylesheet" type="text/css" href="gui/css/skye.css" /> 
</head> 
<body> 

    <h1>Skye</h1> 

    <div id="result"></div> 

    <form id="Skye" name="Skye" method="POST" > 
     <input type="text" id="sentence" name="sentence" autofocus="autofocus" /> 
     <input type="submit" id="display" value="Stuur..." /> 
    </form> 



</body> 
</html> 
+0

Я не думаю, что это причина вашей проблемы, но неопределенная переменная: xml - $ xml = strtolower ($ xml); –

+0

* btw * Здесь нет экранирования для цитат в XPath 1. Вот пример функции, которая решает проблему http://stackoverflow.com/a/27440520/2265374 – ThW

+0

@MattinWashington спасибо, что я пропустил этот. Ты, спасибо! Я буду смотреть в него. – WouterPoel

ответ

2

Ну я нашел проблему с вашим запросом. Если вы ищете точные совпадения и хотите родительский узел вам это нужно:

$nodes = $xpath->query('//neuron/keywords[contains(text(), "wanneer") and contains(text(), "gaat")]/..'); 

так что вы бы заменить implode(' and ', $searchKeywords) с вышесказанным.

Вы также можете обсчитывать вышеупомянутый синтаксис вроде так, как на комментатор ниже:

$nodes = $xpath->query('//neuron[keywords[contains(., "wanneer") or contains(., "gaat")]]'); 

Что это делает?

Ну он смотрит на каждый нейрон выполняет поиск, если текстовое значение <keywords> имеет то, что вы ищете и /.. подобен FilePath, который в основном возвращает родителя. Довольно изящный. Теперь вы можете получить тег <output>.

//Iterate all nodes 
foreach($nodes as $node){ 
    //Find the output node an print its content 
    var_dump($xpath->query('output',$node)->item(0)->textContent); 
} 

Вот мой код в полном объеме, с которым я тестировал. Вы можете скопировать его в тестовый файл, чтобы увидеть результаты и возиться, чтобы вы могли перенести их в свой скрипт.

<?php 

$xml = xml_str(); 
$dom = new DOMDocument(); 
$dom->loadXML($xml); 

$xpath= new DOMXPath($dom); 
$nodes = $xpath->query('//neuron/keywords[contains(text(), "wanneer") or contains(text(), "gaat")]/..'); 

foreach ($nodes as $node) { 
    var_dump($xpath->query('output', $node)->item(0)->textContent); 
} 

function xml_str() 
{ 
    return <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<brain> 
    <neuron> 
     <id>1</id> 
     <input>wie ben jij?</input> 
     <code></code> 
     <output>Ik ben Skye</output> 
     <keywords>wie,ben,jij,Wie,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>2</id> 
     <input>hoe gaat het?</input> 
     <code></code> 
     <output>Met mij gaat het goed. Hoe gaat het me u?</output> 
     <keywords>hoe,gaat,het,Hoe,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>3</id> 
     <input>wat ben jij?</input> 
     <code></code> 
     <output>Ik ben het laatste resultaat in kunstmatige intelligentie die de functies van het menselijk brein kan reproduceren met een grotere snelheid en nauwkeurigheid.</output> 
     <keywords>wat,ben,jij,Wat,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>4</id> 
     <input>hoe zie jij er uit?</input> 
     <code></code> 
     <output></output> 
     <keywords>hoe,zie,jij,er,uit,Hoe,?</keywords> 
     <image><!-- insert binary.jpg from imgLib --></image> 
    </neuron> 
    <neuron> 
     <id>5</id> 
     <input>stel jezelf even voor</input> 
     <code></code> 
     <output>Hoi ik ben Skye, ik ben online gegaan op 17-02-2016.Ik ben het laatste resultaat in kunstmatige intelligentie die de functies van het menselijk brein kan reproduceren met een grotere snelheid en nauwkeurigheid.</output> 
     <keywords>stel,jezelf,even,voor</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>6</id> 
     <input>Welke dag is het vandaag?</input> 
     <code><!-- PHP code om huidige dag weer te geven --></code> 
     <output>Vandaag is het </output> 
     <keywords>welke,dag,is,het,vandaag,?</keywords> 
     <image></image> 
    </neuron> 
    <neuron> 
     <id>7</id> 
     <input>wanneer ben je jarig?</input> 
     <code></code> 
     <output>Ik ben online gegaan op 17 Februari, dus ik ben jarig op 17 Februari :-)</output> 
     <keywords>wanneer,ben,je,jarig,?</keywords> 
     <image><!-- jarig.jpeg from imgLib --></image> 
    </neuron> 
</brain> 
XML; 
} 
?> 
+2

Вы _should_ сможете упростить xpath a немного, используя вложенный предикат и используя '.' вместо' text() ':' // neuron [keywords [contains (., "wanneer") или содержит (., "gaat")]] ' –

+0

Хороший звонок! Обновлено! – DataHerder

Смежные вопросы