Confused how to read the xml object returned by curl in php

This is my php code:

<?php   
if (array_key_exists("site", $_GET) && $_GET["site"] != "" )
{ 
    $url = $_REQUEST['site'];
    $url = " http://api.mywot.com/0.4/public_query2?target=";   
    $result= $url.urlencode($url); 
    $process = curl_init($result); 
    //init curl connection
    curl_setopt($process, CURLOPT_HEADER, 0);    
    curl_setopt($process, CURLOPT_POST, 1); 
    curl_setopt($process, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($process,CURLOPT_CONNECTTIMEOUT,1);
    $resp = curl_exec($process); 
    curl_close($process); 
    header('Content-Type: text/xml');
    $xml = new SimpleXMLElement($resp);
}
?>

Estimated xml:

<?xml version="1.0" encoding="UTF-8"?>
 <query target="example.com">
   <application name="0" r="89" c="44"/>
   <application name="1" r="89" c="46"/>
   <application name="2" r="92" c="47"/>
   <application name="4" r="93" c="48"/>
 </query>

I know how to read this kind of XML file

<Status>
    <code>200</code>
    <request>geocode</request>
</Status>

$status = (int) $xml->Status->code;

The above xml has duplicate tags such as application, how can I read some of them?

+3
source share
3 answers

application elements will be available as an array, for example: $xml->application[3]

$x = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
 <query target="example.com">
   <application name="0" r="89" c="44"/>
   <application name="1" r="89" c="46"/>
   <application name="2" r="92" c="47"/>
   <application name="4" r="93" c="48"/>
 </query>');

 print_r($x); // View entire XML structure

 print_r($x->application[1]); // View the 2nd application item

 echo $x->application[1]['c']; // Get 'c' attribute from 2nd item (46)
+2
source
$xml->application[0];

$xml->application[1];

$xml->application[2];

...
0
source

XPath XML:

$xml->xpath('/query/application[@name=2]')

<application> name = 2. . w3schools XPath tutorial . , XPath PHP SimpleXML, , . XMl-. , DOMDocument. , XPath.

, XMl. $resp FULL-, . , . :

//...
$resp = curl_exec($process);
$resp = substr( $resp, curl_getinfo($process, CURLINFO_HEADER_SIZE) );
curl_close($process); 
//...
0

Source: https://habr.com/ru/post/1785756/


All Articles