How to parse xml with php? [duplicate]

2019-09-22 04:46发布

问题:

Possible Duplicate:
Best XML Parser for PHP
How to parse XML file using php

i could not parse this xml... the real xml is here

    <?xml version="1.0" encoding="ISO-8859-1" ?>
<eqlist>
    <earhquake  name="2012.12.31 18:35:13"  lokasyon="CAMONU-AKHISAR (MANİSA)                           İlksel" lat="38.9572"   lng="27.8965"   mag="2.9" Depth="5.0" />
    <earhquake  name="2012.12.31 18:54:09"  lokasyon="VAN GÖLÜ                                          İlksel" lat="38.7273"   lng="43.1598"   mag="2.3" Depth="2.1" />
    <earhquake  name="2012.12.31 21:00:49"  lokasyon="KUCUKESENCE-ERENLER (SAKARYA)                     İlksel" lat="40.7347"   lng="30.4742"   mag="1.9" Depth="4.4" />
</eqlist>

how can i parse it? the problem is coming from first two chars of the xml file which is running nice remote site's google map application. Look at that array

[0] => ÿþ<?xml version="1.0" encoding="ISO-8859-1" ?>

回答1:

You can use SimpleXML_Load_String.

<?php // RAY_temp_burhan.php
error_reporting(E_ALL);
echo '<pre>';

$xml = <<<ENDXML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<eqlist>
    <earhquake  name="2012.12.31 18:35:13"  lokasyon="CAMONU-AKHISAR (MANISA)                           Ilksel" lat="38.9572"   lng="27.8965"   mag="2.9" Depth="5.0" />
    <earhquake  name="2012.12.31 18:54:09"  lokasyon="VAN GÖLÜ                                          Ilksel" lat="38.7273"   lng="43.1598"   mag="2.3" Depth="2.1" />
    <earhquake  name="2012.12.31 21:00:49"  lokasyon="KUCUKESENCE-ERENLER (SAKARYA)                     Ilksel" lat="40.7347"   lng="30.4742"   mag="1.9" Depth="4.4" />
</eqlist>
ENDXML;

// CONVERT TO AN OBJECT
$obj = SimpleXML_Load_String($xml);

// PARSE OUT SOME ATTRIBUTES
foreach ($obj as $quake)
{
    // ATTRIBUTE NAMES ARE CASE-SENSITIVE
    $loc = $quake->attributes()->lokasyon;
    $dep = $quake->attributes()->Depth;
    echo PHP_EOL . "$loc $dep";
}


回答2:

An object oriented way

$xml = <<<ENDXML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<eqlist>
    <earhquake  name="2012.12.31 18:35:13" 
                lokasyon="CAMONU-AKHISAR (MANISA) Ilksel"
                lat="38.9572"
                lng="27.8965"   mag="2.9" Depth="5.0" />
    <!-- Etc... -->
</eqlist>
ENDXML;

$dom = new DOMDocument();
$dom->loadXML($xml, LIBXML_NOBLANKS);

Then you can use the various methods defined by DOMDocument. One of these methods that is useful for checking the validity with an XSD is schemaValidate