Tôi muốn viết một hàm phân tích cú pháp cấu trúc dữ liệu XML chưa biết (về mặt lý thuyết) thành một mảng PHP tương đương.lặp qua cấu trúc XML không xác định bằng PHP (DOM)
Đây là XML mẫu của tôi:
<?xml version="1.0" encoding="UTF-8"?>
<content>
<title>Sample Text</title>
<introduction>
<paragraph>This is some rudimentary text</paragraph>
</introduction>
<description>
<paragraph>Here is some more text</paragraph>
<paragraph>Even MORE text</paragraph>
<sub_section>
<sub_para>This is a smaller, sub paragraph</sub_para>
<sub_para>This is another smaller, sub paragraph</sub_para>
</sub_section>
</description>
</content>
tôi sửa đổi DOM lặp chức năng này từ devarticles:
$data = 'path/to/xmldoc.xml';
$xmlDoc = new DOMDocument(); #create a DOM element
$xmlDoc->load($data); #load data into the element
$xmlRoot = $xmlDoc->firstChild; #establish root
function xml2array($node)
{
if ($node->hasChildNodes())
{
$subNodes = $node->childNodes;
foreach ($subNodes as $subNode)
{
#filter node types
if (($subNode->nodeType != 3) || (($subNode->nodeType == 3)))
{
$arraydata[$subNode->nodeName]=$subNode->nodeValue;
}
xml2array($subNode);
}
}
return $arraydata;
}
//The getNodesInfo function call
$xmlarray = xml2array($xmlRoot);
// print the output - with a little bit of formatting for ease of use...
foreach($xmlarray as $xkey)
{
echo"$xkey<br/><br/>";
}
Bây giờ, vì cách tôi đi qua các yếu tố để các mảng tôi m ghi đè bất kỳ phần tử nào chia sẻ tên nút (vì tôi lý tưởng muốn cung cấp cho các khóa cùng tên với các nút gốc của chúng). Sự đệ quy của tôi không phải là tuyệt vời ... Tuy nhiên, ngay cả khi tôi làm trống các dấu ngoặc - lớp thứ hai của các nút vẫn đang đến như là giá trị trên tầng đầu tiên (xem văn bản của nút mô tả).
Bất kỳ ai có ý tưởng nào về cách tôi có thể xây dựng tốt hơn điều này?
hoạt động giải quyết vấn đề - giải quyết vấn đề! – sunwukung