我试图从Wikidata访问以下属性: 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 -美国跨国互联网和技术公司,variable5 - 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>发布于 2014-12-15 01:45:22
你需要显示你想解析的JSON ..。
基本上,您可以像这样从PHP中从JSON中获取值..。
如果$doc是您要解析的JSON
$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];了解您在那里做什么之后,编辑:-)
嗨,对不起,我完全搞不懂你在那里做什么……所以我在我的服务器上测试了你的代码然后得到你想要的.
按照你想要的密码..。我取了明确的变量名,所以它们长了一点,但更容易理解.
$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>");
}https://stackoverflow.com/questions/27476094
复制相似问题