Reputation: 12412
I have an XML document that looks something like:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<smses count="1992">
<sms protocol="0" address="5558675309" date="1309444177931" type="1" subject="null" body="text message" toa="0" sc_toa="0" service_center="null" read="1" status="-1" locked="0" />
</smses>
I want to extract the address, date, and body for each <sms>
line, and there's about 8000 lines. I'm not sure the best way to go about this, so if anyone could point me in the right direction, I'd appreciate it. Don't really need specific code, just direction. I'm stumped.
Upvotes: 0
Views: 2078
Reputation: 25572
You can use PHP's SimpleXML extension to parse this. See "Basic SimpleXML usage" for an introduction.
Here's some code to get you started (array_map
requires PHP >= 5.3):
$smses = new SimpleXMLElement($xml_str);
$smses_parsed = array_map(function($sms_el) {
return array('address' => (string)$sms_el['address'],
'date' => (int)$sms_el['date'],
'body' => (string)$sms_el['body']);
}, $smses);
print_r($smses_parsed[0]); /* => array("address" => "5558675309",
"date" => 1309444177931,
"body" => "text message") */
One note: SimpleXML is a strict parser. If your XML is somewhat malformed, you'll probably have more luck with DOMDocument
. (I don't expect that case to be likely here, though, given the simple document structure you posted.)
Upvotes: 2
Reputation: 14568
$dom = new DOMDOcument();
// Load your XML as a string
$dom->loadXML($s);
// Create new XPath object
$xpath = new DOMXpath($dom);
// Query for Account elments inside NewDataSet elemts inside string elements
$result = $xpath->query("/smses");
// Note there are many ways to query XPath using this syntax
// Iterate over the results
foreach($result as $node)
{
// Obtains item for sms tags here
}
Upvotes: 2