2

I am trying to capture the first instance of particular elements from an object. I have an object $doc and would like to get the values of the following.

id, url, alias, description and label i.e. specifically:

  • variable1 - Q95,
  • variable2 - //www.wikidata.org/wiki/Q95,
  • variable3 - Google.Inc,
  • varialbe4 - American multinational Internet and technology corporation,
  • variable5 - Google

I've made some progress getting the $jsonArr string however I'm not sure this is the best way to go, and if so I'm not sure how to progress anyway. Please advise as to the best way to get these. Please see my code below:

<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

0

由于对 API 请求的响应是 JSON,而不是 HTML 或 XML,因此使用 cURL 或 Stream 库来执行 HTTP 请求是最合适的。你甚至可以使用一些原始的东西,比如file_get_contents.

例如,使用 cURL:

// Make the request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.wikidata.org/w/api.php?action=wbsearchentities&search=google&format=json&language=en");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

// Decode the string into an appropriate PHP type
$contents = json_decode($output);

// Navigate the object
$contents->search[0]->id; // "Q95"
$contents->search[0]->url; // "//www.wikidata.org/wiki/Q95"
$contents->search[0]->aliases[0]; // "Google Inc."

您可以像使用任何 PHP 对象一样var_dump检查和遍历它。$contents

于 2014-12-18T02:50:46.990 回答