1

我正在尝试从 Wikidata API 访问以下属性:id、url、别名、描述和标签,但到目前为止还没有成功。我确定我犯了基本错误,到目前为止只有以下代码。非常感谢有关访问此数据的最佳方式的任何建议。

<html>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>

<?php

if (isset($_POST['q'])) {
$search = $_POST['q']; 
$errors = libxml_use_internal_errors(true);    
$doc = new DOMDocument();    
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php? 
action=wbsearchentities&search=Google&format=json&language=en");    
libxml_clear_errors();
libxml_use_internal_errors($errors);   
}
?>
</body>
</html>

编辑 - 我设法得到一个包含我想要的特定数据的字符串 ($jsonArr)。但是,我想从字符串中获取特定元素的第一个实例,特别是 id、url、别名、描述和标签,即:variable1 - Q95, variable2 - //www.wikidata.org/wiki/Q95, variable3 - Google .Inc,varialbe4 - 美国跨国互联网和技术公司,varial5 - Google/ 请参见下面的代码:

<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>

<?php
if (isset($_POST['q'])) {
$search = $_POST['q']; 
$errors = libxml_use_internal_errors(true);    
$doc = new DOMDocument();     
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");    
libxml_clear_errors();
libxml_use_internal_errors($errors); 

var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;

$jsonArr = (string)$jsonArr;
echo $jsonArr; 

}
?>
</body>
</HTML>
4

1 回答 1

1

您需要显示要解析的 JSON...

基本上,您可以像这样从 PHP 中的 JSON 中获取值...

如果 $doc 是您要解析的 JSON

$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];

在了解您在那里做什么后进行编辑:-)

嗨,对不起,我对你在那里所做的事情完全感到困惑......所以我已经在我的服务器上测试了你的代码,只是得到你想要的......

按照您想要的代码...我采用了清晰的 var 名称,所以它们有点长,但更容易理解...

$searchString = urlencode($_POST['q']); //Encode your Searchstring for url
$resultJSONString = file_get_contents("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=".$searchString."&format=json&language=en"); //Get your Data from wiki
$resultArrayWithHeader = json_decode($resultJSONString, true); //Make an associative Array from respondet JSON
$resultArrayClean = $resultArrayWithHeader["search"]; //Get the search Array and ignore the header part

for ($i = 0; $i < count($resultArrayClean); $i++) { //Loop through the search results
    echo("<b>Entry: ".$i."</b>");
    echo("<br>");
    echo($resultArrayClean[$i]["id"]); //Search results value of key 'id' at position n
    echo("<br>");
    echo($resultArrayClean[$i]["url"]); //Search results value of key 'url' at position n
    echo("<br>");
    echo($resultArrayClean[$i]["aliases"]); //Search results value of key 'aliases' at position n
    echo("<br>");
    echo("<br>");
    echo("<br>");
}
于 2014-12-15T01:45:22.483 回答