Search code examples
phpxmlsimplexml

How to use foreach with PHP & XML


This is my php code

$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>";
}

This is my XML File:

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

Expected Result

 <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>

Iam new to PHP and i am not very well sure on how to handle the xml output? If anyone can help me on this pls do that. Appreciate your help.


Solution

  • Do like this. You have passes object instead of array. Json decode and encode 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>";
                   }