如何将 foreach 与 PHP & XML 一起使用

How to use foreach with PHP & XML

这是我的php代码

$xmldata = simplexml_load_string($ops_response);

foreach($xmldata->world-patent-data->biblio-search->search-result->exchange-documents->exchange-document->bibliographic-data->parties as $item)
{
echo "<p>Applicant Name: " . $item->applicants->applicant->applicant-name->name . "</p>";
echo "<p>Doc Number: " . $item->applicants->applicant->applicant-name->doc-number . "</p>";
echo "<p>Description: " . $item->applicants->applicant->applicant-name->abstract . "</p>";
}

这是我的 XML 文件:

https://ipappatent.com/xml/document.xml

预期结果

 <p>Applicant Name: PHYLION BATTERY CO LTD</p>
 <p>Doc Number: 2018101613</p>
 <p>Description: A frame tube having a battery enclosure structure for an electric bike. The frame tube comprises a main body</p>


 <p>Year: ASTRO ENGINEERING CO LTD [TW]</p>
 <p>Category: 20180821</p>
 <p>Country: A drive assemblage is described for a vehicle drivable by muscle energy and/or—in particular additionally—by motor energy</p>

我是 PHP 的新手,我不太确定如何处理 xml 输出?如果有人可以帮助我,请这样做。感谢您的帮助。

libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
  <user>John Doe</wronguser>
  <email>john@example.com</wrongemail>
</document>";

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
    echo "Failed loading XML: ";
    foreach(libxml_get_errors() as $error) {
        echo "<br>", $error->message;
    }
} else {
    print_r($xml);
}
?>

你好,试试这个

这样做。您传递的是对象而不是数组。 Json 解码和编码 simplexml_load_string($ops_response)

$string = //"your xml string here";

    echo "<pre>";
            $json = json_decode(json_encode((array) simplexml_load_string($string)), 1);

    print_r($json);
    $json = $json['biblio-search']['search-result']['exchange-documents'];
    foreach($json as $item)
                {
                echo "<p>Applicant Name: " . $item['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'][0]['applicant-name']['name'] . "</p>";

echo "<p>Description: " . $item['exchange-document']['abstract']['@attributes']['lang'] . "</p>";
               }